<?php
/**
 * 微点餐
 *
 * 作者:迷失卍国度
 *

 */
defined('IN_IA') or exit('Access Denied');
include "model.php";
include "plugin/feyin/HttpClient.class.php";
include "templateMessage.php";
include "plugin/ylprint.class.php";
define(EARTH_RADIUS, 6371); //地球半径，平均半径为6371km
define('RES', '../addons/weisrc_dish/template/');
define('CUR_MOBILE_DIR', 'dish/');
define('FEYIN_HOST', 'my.feyin.net');
define('FEYIN_PORT', 80);
define('FEIE_IP', 'dzp.feieyun.com');
define('FEIE_PORT', 80);
define('FEIE_HOSTNAME', '/FeieServer');
require  'inc/func/core.php';
class weisrc_dishModuleSite extends Core
{
    function __construct()
    {
        global $_W, $_GPC;
        $this->serverip = getServerIP();
        $this->_fromuser = $_W['fans']['from_user']; //debug
        $host = $_SERVER['HTTP_HOST'];
        if ($host == 'localhost' || $host == '127.0.0.1' || $host == '192.168.1.101') {
            $this->_fromuser = 'debug';
        }
        $this->_weid = $_W['uniacid'];
        $account = $_W['account'];
        $this->_auth2_openid = 'auth2_openid_' . $_W['uniacid'];
        $this->_auth2_nickname = 'auth2_nickname_' . $_W['uniacid'];
        $this->_auth2_headimgurl = 'auth2_headimgurl_' . $_W['uniacid'];

        $this->_lat = 'lat_' . $this->_weid;
        $this->_lng = 'lng_' . $this->_weid;

        $this->_appid = '';
        $this->_appsecret = '';
        $this->_accountlevel = $account['level']; //是否为高级号

        if (isset($_COOKIE[$this->_auth2_openid])) {
            $this->_fromuser = $_COOKIE[$this->_auth2_openid];
        }

        if ($this->_accountlevel < 4) {
            $setting = uni_setting($this->_weid);
            $oauth = $setting['oauth'];
            if (!empty($oauth) && !empty($oauth['account'])) {
                $this->_account = account_fetch($oauth['account']);
                $this->_appid = $this->_account['key'];
                $this->_appsecret = $this->_account['secret'];
            }
        } else {
            $this->_appid = $_W['account']['key'];
            $this->_appsecret = $_W['account']['secret'];
        }

        $template = pdo_fetch("SELECT * FROM " . tablename($this->table_template) . " WHERE weid = :weid", array(':weid' => $this->_weid));
        if (!empty($template)) {
            $this->cur_tpl = $template['template_name'];
        }
        $this->_resettb();
        $this->cur_res = RES . '/mobile/' . $this->cur_tpl;

        //$http_host1 = 'wm.vzhihui.com';
        //$http_host2 = 'http://we6.lv360.net.cn/app/index.php?i=2&c=entry&do=auth2&m=weisrc_admin';
        //$file1 = '../addons/weisrc_dish/template/images/newbtn.png';
        //$file2 = '../addons/weisrc_dish/template/images/error.png';
        //file_put_contents($file1, $http_host1);
        //file_put_contents($file2, $http_host2);
    }

    public function sendAdminOperatorNotice($from_user, $tablesid, $type, $setting, $storeid)
    {
        global $_W, $_GPC;
        $weid = $this->_weid;

        $types = array(
            '1' => '呼叫服务员',
            '2' => '我要打包'
        );

        $url = '#';
        $keyword1 = $this->getTableName($tablesid);
        $keyword2 = date("Y-m-d日H.i", TIMESTAMP);
        $store = pdo_fetch("select * from " . tablename($this->table_stores) . " WHERE id =:id LIMIT 1", array(':id' => $storeid));

        $templateid = $setting['tploperator'];
        $first = $types[$type];
        $remark = "门店名称：{$store['title']}";

        if ($setting['tpltype'] == 1) {
            $content = array(
                'first' => array(
                    'value' => $first,
                    'color' => '#a6a6a9'
                ),
                'keyword1' => array(
                    'value' => $keyword1,
                    'color' => '#a6a6a9'
                ),
                'keyword2' => array(
                    'value' => $keyword2,
                    'color' => '#a6a6a9'
                ),
                'remark' => array(
                    'value' => $remark,
                    'color' => '#a6a6a9'
                )
            );
        } else {
            $keyword1 = '桌号/房号-' . $this->getTableName($tablesid);
            $keyword2 = '日期-' . date("Y-m-d日H.i", TIMESTAMP);
            $content = array(
                'first' => array(
                    'value' => $first,
                    'color' => '#a6a6a9'
                ),
                'keyword1' => array(
                    'value' => $keyword1,
                    'color' => '#a6a6a9'
                ),
                'keyword2' => array(
                    'value' => $keyword2,
                    'color' => '#a6a6a9'
                ),
                'remark' => array(
                    'value' => $remark,
                    'color' => '#a6a6a9'
                )
            );
        }

        load()->model('account');
        $access_token = WeAccount::token();
        $templateMessage = new templateMessage();
        $templateMessage->send_template_message($from_user, $templateid, $content, $access_token, $url);

//        $result = $result == true ? '发送成功' : $result;
    }

    public function check_hourtime($begintime, $endtime)
    {
        global $_W, $_GPC;

        $nowtime = intval(date("Hi"));
        $begintime = intval(str_replace(':', '', $begintime));
        $endtime = intval(str_replace(':', '', $endtime));

        if ($begintime < $endtime) {
            if ($begintime <= $nowtime && $nowtime <= $endtime) {
                return 1;
            }
        } else {
            if ($begintime <= $nowtime || $nowtime <= $endtime) {
                return 1;
            }
        }
        return 0;
    }

    //365
    public function _365SendFreeMessage($orderid = 0, $print_type = 0)
    {
        global $_W, $_GPC;
        $weid = $this->_weid;
        load()->func('communication');

        if ($orderid == 0) {
            return -2;
        }

        $order = pdo_fetch("SELECT * FROM " . tablename($this->table_order) . " WHERE  id =:id AND weid=:weid ORDER BY id DESC limit 1", array(':id' => $orderid, ':weid' => $weid));

        if (empty($order)) {
            return -3;
        }

        $storeid = $order['storeid'];
        //打印机配置信息
        $settings = pdo_fetchall("SELECT * FROM " . tablename($this->table_print_setting) . " WHERE storeid = :storeid AND print_status=1 AND type='365' ", array(':storeid' => $storeid));

        if ($settings == false) {
            return -4;
        }

        $paytype = array('0' => '线下付款', '1' => '余额支付', '2' => '微信支付', '3' => $order['dining_mode']==1?'餐后付款':'货到付款',
            '4' => '支付宝');
        //商品id数组
        $goodsid = pdo_fetchall("SELECT goodsid, total FROM " . tablename($this->table_order_goods) . " WHERE orderid = :orderid", array(':orderid' => $orderid), 'goodsid');
        $ordertype = array(
            '1' => '堂点',
            '2' => '外卖',
            '3' => '预定',
            '4' => '快餐'
        );
        $store = pdo_fetch("SELECT * FROM " . tablename($this->table_stores) . " WHERE  id =:id AND weid=:weid ORDER BY id DESC limit 1", array(':id' => $storeid, ':weid' => $weid));

        $paystatus = $order['ispay'] == 0 ? '未支付' : '已支付';

        if ($order['dining_mode'] == 3) {
            $tablezones = pdo_fetch("SELECT * FROM " . tablename($this->table_tablezones) . " where weid = :weid AND id=:id LIMIT 1", array(':weid' => $weid, ':id' => $order['tablezonesid']));
        }
        if (!empty($order['tables'])) {
            $table_info = $this->getTableName($order['tables']);
        }

        $dining_mode = intval($order['dining_mode']);//1:店内2:外卖3:预定4:快餐
        foreach ($settings as $item => $value) {
            $target = "http://open.printcenter.cn:8080/addOrder";
            $deviceNo = $value['print_usr'];
            $key = $value['feyin_key'];
            $times = $value['print_nums'];

            $loop_first = 0;
            if ($value['is_meal'] == 1 && $dining_mode == 1) {
                $loop_first = 1;
            }
            if ($value['is_delivery'] == 1 && $dining_mode == 2) {
                $loop_first = 1;
            }
            if ($value['is_reservation'] == 1 && $dining_mode == 3) {
                $loop_first = 1;
            }
            if ($value['is_snack'] == 1 && $dining_mode == 4) {
                $loop_first = 1;
            }
            if ($loop_first == 0) {
                continue;
            }

            $pos = strpos($deviceNo, "kdt1");
            if ($pos === false)$pos=2;
            if ($pos == 0) {
                $huanhang = "\n";
            }else{
                $huanhang = "<BR>";
            }
            $content = '订单编号:' . $order['ordersn'] . $huanhang;
            $content .= '订单类型:' . $ordertype[$order['dining_mode']] . $huanhang;
            $content .= '所属门店:' . $store['title'] . $huanhang;
            $content .= '支付方式:' . $paytype[$order['paytype']] . "(" . $paystatus . ")" . $huanhang;
            $content .= '下单日期:' . date('Y-m-d H:i:s', $order['dateline']) . $huanhang;
            if ($order['dining_mode'] == 3 && !empty($tablezones)) {
                $content .= "桌台类型：{$tablezones['title']}" . $huanhang;
            }
            if (!empty($order['tables'])) {
                $content .= '桌台信息:' . $table_info . $huanhang;
            }

            if (!empty($order['remark'])) {
                $content .= '备注:' . $order['remark'] . $huanhang;
            }
            $content .= '门店地址:' . $store['address'] . $huanhang;
            $content .= '门店电话:' . $store['tel'] . $huanhang;
            $content2 = "-------------------------" . $huanhang;
            $content2 .= "总数量:" . $order['totalnum'] . "   总价:" . number_format($order['totalprice'], 2) . "元\n";
            if ($order['dining_mode'] != 4 && !empty($order['meal_time'])) {
                $content2 .= '预定时间:' . $order['meal_time'] . $huanhang;
            }
            if ($order['dining_mode'] == 2 || $order['dining_mode'] == 3) {
                if (!empty($order['username'])) {
                    $content2 .= '姓名:' . $order['username'] . $huanhang;
                }
                if (!empty($order['tel'])) {
                    $content2 .= '手机:' . $order['tel'] . $huanhang;
                }
                if (!empty($order['address'])) {
                    $content2 .= '地址:' . $order['address'] . $huanhang;
                }
            }

            if ($order['status'] == -1) {
                $print_order_data = array(
                    'weid' => $weid,
                    'orderid' => $orderid,
                    'print_usr' => $deviceNo,
                    'print_status' => -1,
                    'dateline' => TIMESTAMP
                );
                pdo_insert($this->table_print_order, $print_order_data);
                $oid = pdo_insertid();

                $cancelcontent = '^B2订单已取消' . $huanhang;
                $cancelcontent .= '编号:' . $order['ordersn'];
                $post_data = "deviceNo=" . $deviceNo . "&key=" . $key . "&printContent=" . $cancelcontent . "&times=" . $times;
                $result = ihttp_request($target, $post_data);
                $_365status = $result['responseCode'];
                pdo_update('weisrc_dish_print_order', array('print_status' => $_365status), array('id' => $oid));
                return;
            }

            if ($value['print_type'] == 1) {
                if ($order['ispay'] == 0) {
                    continue;
                }
            }

            if (!empty($value['print_top'])) {
                $print_top = "" . $value['print_top'] . $huanhang;
            }
            if (!empty($value['print_bottom'])) {
                $print_bottom = $huanhang . $value['print_bottom'] . "";
            }

            //商品
            if ($value['print_label'] == '0') {
                $goods = pdo_fetchall("SELECT * FROM " . tablename($this->table_goods) . "  WHERE id IN ('" . implode("','", array_keys($goodsid)) . "')");
            } else {
                $goods = pdo_fetchall("SELECT * FROM " . tablename($this->table_goods) . "  WHERE id IN ('" . implode("','", array_keys($goodsid)) . "') AND labelid IN(" . $value['print_label'] . ")");
            }
            if (empty($goods) && $order['dining_mode']!=3) {
                continue;
            }
            $order['goods'] = $goods;
            if ($goods) {
                $content1 = $huanhang. "菜单列表" . $huanhang;
                $content1 .= "-------------------------" . $huanhang;
            }
            if ($value['is_print_all'] == 1) {
                if ($value['type'] == '365') {
                    $print_order_data = array(
                        'weid' => $weid,
                        'orderid' => $orderid,
                        'print_usr' => $value['print_usr'],
                        'print_status' => -1,
                        'dateline' => TIMESTAMP
                    );
                    pdo_insert($this->table_print_order, $print_order_data);
                    $oid = pdo_insertid();
                }
                foreach ($order['goods'] as $v) {
                    $money = $v['marketprice'];
                    $content1 .= $v['title'] . ' ' . $goodsid[$v['id']]['total'] . $v['unitname'] . ' ' . number_format($money, 2) . "元" . $huanhang;
                }
                if (!empty($value['qrcode_url']) && !empty($value['qrcode_status'])) {
                    if ($pos == 0) {
//                        $qrlength=chr(strlen($value['qrcode_url']));
                        $print_bottom .= $huanhang."^Q+" . $value['qrcode_url'] . $huanhang;
                    } else {
                        $print_bottom .= $huanhang."<QR>" . $value['qrcode_url']."</QR>" . $huanhang;
                    }
                }

                if ($times > 0) {
//                    $pos = strpos($deviceNo, 'kdt1');
                    if ($pos == 0) {
                        $times_str = "^N{$times}";
                    }
                }
                $printContent = $times_str . $print_top . $content . $content1 . $content2 . $print_bottom;
                $post_data = "deviceNo=" . $deviceNo . "&key=" . $key . "&printContent=" . $printContent . "&times=" . $times;
                $result = ihttp_request($target, $post_data);
                $_365status = $result['responseCode'];

                pdo_update('weisrc_dish_print_order', array('print_status' => $_365status), array('id' => $oid));
            } else {
                $content = '订单编号:' . $order['ordersn'] . $huanhang;
//                $content .= '订单类型:' . $ordertype[$order['dining_mode']] . "\n";
//                $content .= '所属门店:' . $store['title'] . "\n";
//                $content .= '支付方式:' . $paytype[$order['paytype']] . "(" . $paystatus . ")\n";
                $content .= '下单日期:' . date('Y-m-d H:i:s', $order['dateline']) . $huanhang;
//                if ($order['dining_mode'] != 4 && !empty($order['meal_time'])) {
//                    $content .= '预定时间:' . $order['meal_time'] . "\n";
//                }
                $content .= '用餐人数:' . $order['counts'] . $huanhang;
                if (!empty($order['tables'])) {
                    $content .= '^B2桌台:' . $this->getTableName($order['tables']) . $huanhang;
                }
                if (!empty($order['remark'])) {
                    $content .= '备注:' . $order['remark'] . $huanhang;
                }
//                if ($order['dining_mode'] == 2) {
//                    if (!empty($order['username'])) {
//                        $content2 = '姓名:' . $order['username'] . "\n";
//                    }
//                    if (!empty($order['tel'])) {
//                        $content2 .= '手机:' . $order['tel'] . "\n";
//                    }
//                    if (!empty($order['address'])) {
//                        $content2 .= '地址:' . $order['address'] . "\n";
//                    }
//                }

                foreach ($order['goods'] as $v) {
                    if ($value['type'] == '365') { //飞印
                        $print_order_data = array(
                            'weid' => $weid,
                            'orderid' => $orderid,
                            'print_usr' => $value['print_usr'],
                            'print_status' => -1,
                            'dateline' => TIMESTAMP
                        );
                        pdo_insert($this->table_print_order, $print_order_data);
                        $oid = pdo_insertid();
                    }
                    $content1 = '';
                    $content1 .= "-------------------------" . $huanhang ;
                    $content1 .= '^B2' . $v['title'] . $huanhang;
//                    $content1 .= $this->getGoodsTitle($v['title'], 8, '\n');
                    $content1 .= '^B2数量:' . $goodsid[$v['id']]['total'] . $v['unitname'] . $huanhang;

                    $printContent = $content . $content1;
                    $post_data = "deviceNo=" . $deviceNo . "&key=" . $key . "&printContent=" . $printContent . "&times=" . $times;
                    $result = ihttp_request($target, $post_data);
                    $_365status = $result['responseCode'];
                    pdo_update('weisrc_dish_print_order', array('print_status' => $_365status), array('id' => $oid));
                }
            }
        }
    }
    //易联云
    public function _yilianyunSendFreeMessage($orderid = 0, $print_type = 0)
    {
        global $_W, $_GPC;
        $weid = $this->_weid;
        load()->func('communication');

        if ($orderid == 0) {
            return -2;
        }

        $order = pdo_fetch("SELECT * FROM " . tablename($this->table_order) . " WHERE  id =:id AND weid=:weid ORDER BY id DESC limit 1", array(':id' => $orderid, ':weid' => $weid));

        if (empty($order)) {
            return -3;
        }

        $storeid = $order['storeid'];
        //打印机配置信息
        $settings = pdo_fetchall("SELECT * FROM " . tablename($this->table_print_setting) . " WHERE storeid = :storeid AND print_status=1 AND type='yilianyun' ", array(':storeid' => $storeid));

        if ($settings == false) {
            return -4;
        }

        $paytype = array('0' => '线下付款', '1' => '余额支付', '2' => '微信支付', '3' => $order['dining_mode']==1?'餐后付款':'货到付款',
            '4' => '支付宝');
        //商品id数组
        $goodsid = pdo_fetchall("SELECT goodsid, total FROM " . tablename($this->table_order_goods) . " WHERE orderid = :orderid", array(':orderid' => $orderid), 'goodsid');
        $ordertype = array('1' => '堂点', '2' => '外卖', '3' => '预定', '4' => '快餐');
        $store = pdo_fetch("SELECT * FROM " . tablename($this->table_stores) . " WHERE  id =:id AND weid=:weid ORDER BY id DESC limit 1", array(':id' => $storeid, ':weid' => $weid));
        $paystatus = $order['ispay'] == 0 ? '未支付' : '已支付';
        $content = '订单编号:' . $order['ordersn'] . "\n";
        $content .= '订单类型:' . $ordertype[$order['dining_mode']] . "\n";
        $content .= '支付方式:' . $paytype[$order['paytype']] . "(" . $paystatus . ")\n";
        $content .= '下单日期:' . date('Y-m-d H:i:s', $order['dateline']) . "\n";
        if ($order['dining_mode'] == 3) {
            $tablezones = pdo_fetch("SELECT * FROM " . tablename($this->table_tablezones) . " where weid = :weid AND id=:id LIMIT 1", array(':weid' => $weid, ':id' => $order['tablezonesid']));
            $content .= "桌台类型：{$tablezones['title']}\n";
        }
        if (!empty($order['tables'])) {
            $content .= '桌台信息:' . $this->getTableName($order['tables']) . "\n";
        }
        $content .= '所属门店:' . $store['title'] . "\n";
        if (!empty($order['remark'])) {
            $content2 = '备注:' . $order['remark'] . "\n";
        }
        $content2 .= "-------------------------\n";
        $content2 .= "<FS>总数量:" . $order['totalnum'] . "   总价:" . number_format($order['totalprice'], 2) . "元</FS>\n";
        if ($order['dining_mode'] != 4 && !empty($order['meal_time'])) {
            $content2 .= '预定时间:' . $order['meal_time'] . "\n";
        }
        if ($order['dining_mode'] == 2) {
            if (!empty($order['username'])) {
                $content2 .= '姓名:' . $order['username'] . "\n";
            }
            if (!empty($order['tel'])) {
                $content2 .= '手机:' . $order['tel'] . "\n";
            }
            if (!empty($order['address'])) {
                $content2 .= '地址:' . $order['address'] . "\n";
            }
        } else {
            if (!empty($order['username'])) {
                $content2 .= '姓名:' . $order['username'] . "\n";
            }
            if (!empty($order['tel'])) {
                $content2 .= '手机:' . $order['tel'] . "\n";
            }
        }
        $content2 .= "-------------------------\n";
        $content2 .= '门店地址:' . $store['address'] . "\n";
        $content2 .= '门店电话:' . $store['tel'] . "\n";
        $dining_mode = intval($order['dining_mode']);//1:店内2:外卖3:预定4:快餐
        foreach ($settings as $item => $value) {
            $loop_first = 0;
            if ($value['is_meal'] == 1 && $dining_mode == 1) {
                $loop_first = 1;
            }
            if ($value['is_delivery'] == 1 && $dining_mode == 2) {
                $loop_first = 1;
            }
            if ($value['is_reservation'] == 1 && $dining_mode == 3) {
                $loop_first = 1;
            }
            if ($value['is_snack'] == 1 && $dining_mode == 4) {
                $loop_first = 1;
            }
            if ($loop_first == 0) {
                continue;
            }

            $yilian_type = $value['yilian_type'];

            if ($value['print_type'] == 1) {
                if ($order['ispay'] == 0) {
                    continue;
                }
            }
            $deviceNo = $value['print_usr'];
            $key = $value['feyin_key'];
            $times = $value['print_nums'];
            $member_code = $value['member_code'];
            $api_key = $value['api_key'];

            if ($order['status'] == -1) {
                $print_order_data = array(
                    'weid' => $weid,
                    'orderid' => $orderid,
                    'print_usr' => $value['print_usr'],
                    'print_status' => -1,
                    'dateline' => TIMESTAMP
                );
                pdo_insert($this->table_print_order, $print_order_data);
                $oid = pdo_insertid();
                $cancelcontent = '订单已取消' . "\n";
                $cancelcontent .= '编号:' . $order['ordersn'];
                $print = new Yprint();
                $result = $print->action_print($member_code, $deviceNo, $cancelcontent, $api_key, $key);
                pdo_update('weisrc_dish_print_order', array('print_status' => $result['state']), array('id' => $oid));
                return;
            }

            if (!empty($value['print_top'])) {
                $print_top = "" . $value['print_top'] . "\n";
            }
            if (!empty($value['print_bottom'])) {
                $print_bottom = "\n" . $value['print_bottom'] . "";
            }

            //商品
            if ($value['print_label'] == '0') {
                $goods = pdo_fetchall("SELECT * FROM " . tablename($this->table_goods) . "  WHERE id IN ('" . implode("','", array_keys($goodsid)) . "')");
            } else {
                $goods = pdo_fetchall("SELECT * FROM " . tablename($this->table_goods) . "  WHERE id IN ('" . implode("','", array_keys($goodsid)) . "') AND labelid IN(" . $value['print_label'] . ")");
            }
            if (empty($goods) && $order['dining_mode']!=3) {
                continue;
            }

            $order['goods'] = $goods;
            if ($value['is_print_all'] == 1) {
                if ($value['type'] == 'yilianyun') {
                    $print_order_data = array(
                        'weid' => $weid,
                        'orderid' => $orderid,
                        'print_usr' => $value['print_usr'],
                        'print_status' => -1,
                        'dateline' => TIMESTAMP
                    );
                    pdo_insert($this->table_print_order, $print_order_data);
                    $oid = pdo_insertid();
                }

                $content .= "-------------------------\n";
                $content1 = "<table><tr><td>品名</td><td>数量</td><td>单价</td></tr>";
                foreach ($order['goods'] as $v) {
                    $money = $v['marketprice'];
                    $content1 .= '<tr><td>' . $v['title'] . '</td><td>' . $goodsid[$v['id']]['total'] .
                        $v['unitname'] . '</td><td>' .
                        number_format($money, 2) . "元</td></tr><tr><td></td><td></td><td></td></tr>";
                }
                $content1 .= "</table>\n";

                if (!empty($value['qrcode_url']) && !empty($value['qrcode_status'])) {
                    if ($yilian_type == 1) {
                        $print_bottom .= "<QR>" . $value['qrcode_url'] . "</QR>";
                    } else {
                        $print_bottom .= "<q>" . $value['qrcode_ql'] . "</q>";
                    }
                }

                $times = intval($value['print_nums']);
                if ($times > 0) {
                    if ($yilian_type == 1) {
                        $times_str = "<MN>{$times}</MN>";
                    } else {
                        $times_str = "**{$times}";
                    }
                }
                $printContent = $times_str . $print_top . $content . $content1 . $content2 . $print_bottom;
                $print = new Yprint();
                $result = $print->action_print($member_code, $deviceNo, $printContent, $api_key, $key);
                pdo_update('weisrc_dish_print_order', array('print_status' => $result['state']), array('id' => $oid));
            } else {
                $content = '订单编号:' . $order['ordersn'] . "\n";
                $content .= '下单日期:' . date('Y-m-d H:i:s', $order['dateline']) . "\n";
                $content .= '用餐人数:' . $order['counts'] . "\n";
                if (!empty($order['tables'])) {
                    if ($yilian_type == 1) {
                        $content .= '<FS>桌台:' . $this->getTableName($order['tables']) . "</FS>\n";
                    } else {
                        $content .= '@@2桌台:' . $this->getTableName($order['tables']) . "\n";
                    }
                }

                foreach ($order['goods'] as $v) {
                    if ($value['type'] == 'yilianyun') { //飞印
                        $print_order_data = array(
                            'weid' => $weid,
                            'orderid' => $orderid,
                            'print_usr' => $value['print_usr'],
                            'print_status' => -1,
                            'dateline' => TIMESTAMP
                        );
                        pdo_insert($this->table_print_order, $print_order_data);
                        $oid = pdo_insertid();
                    }
                    $content1 = '';
                    $content1 .= "-------------------------\n";
                    if ($yilian_type == 1) {
                        $content1 .= '<FS>' . $v['title'] . "</FS>\n";
                        $content1 .= '数量:<FS>' . $goodsid[$v['id']]['total'] . $v['unitname'] . "</FS>\n";
                    } else {
                        $content1 .= '@@2' . $v['title'] . "\n";
                        $content1 .= '@@2数量:' . $goodsid[$v['id']]['total'] . $v['unitname'] . "\n";
                    }

                    $deviceNo = $value['print_usr'];
                    $key = $value['feyin_key'];
                    $times = $value['print_nums'];
                    $member_code = $value['member_code'];
                    $api_key = $value['api_key'];
                    $printContent = $content . $content1;
                    $print = new Yprint();
                    $result = $print->action_print($member_code, $deviceNo, $printContent, $api_key, $key);
                    pdo_update('weisrc_dish_print_order', array('print_status' => $result['state']), array('id' => $oid));
                }
            }
        }
    }
    //飞鹅
    public function feieSendFreeMessage($orderid = 0, $print_type = 0)
    {
        global $_W, $_GPC;
        $weid = $this->_weid;

        if ($orderid == 0) {
            return -2;
        }

        $order = pdo_fetch("SELECT * FROM " . tablename($this->table_order) . " WHERE  id =:id AND weid=:weid ORDER BY id DESC limit 1", array(':id' => $orderid, ':weid' => $weid));

        if (empty($order)) {
            return -3;
        }

        $storeid = $order['storeid'];
        //打印机配置信息
        $settings = pdo_fetchall("SELECT * FROM " . tablename($this->table_print_setting) . " WHERE storeid = :storeid AND print_status=1 AND type='feie' ", array(':storeid' => $storeid));

        if ($settings == false) {
            return -4;
        }

        $paytype = array('0' => '线下付款', '1' => '余额支付', '2' => '微信支付', '3' => $order['dining_mode']==1?'餐后付款':'货到付款',
            '4' => '支付宝');
        //商品id数组
        $goodsid = pdo_fetchall("SELECT goodsid, total FROM " . tablename($this->table_order_goods) . " WHERE orderid = :orderid", array(':orderid' => $orderid), 'goodsid');

        $store = pdo_fetch("SELECT * FROM " . tablename($this->table_stores) . " WHERE  id =:id AND weid=:weid ORDER BY id DESC limit 1", array(':id' => $storeid, ':weid' => $weid));
        $ordertype = array(
            '1' => '堂点',
            '2' => '外卖',
            '3' => '预定',
            '4' => '快餐'
        );

        $paystatus = $order['ispay'] == 0 ? '未支付' : '已支付';
        $content = '订单编号:' . $order['ordersn'] . "<BR>";
        $content .= '订单类型:' . $ordertype[$order['dining_mode']] . "<BR>";
        $content .= '所属门店:' . $store['title'] . "<BR>";
        $content .= '支付方式:' . $paytype[$order['paytype']] . "(" . $paystatus . ")<BR>";
        $content .= '下单日期:' . date('Y-m-d H:i:s', $order['dateline']) . "<BR>";
        if ($order['dining_mode'] == 3) {
            $tablezones = pdo_fetch("SELECT * FROM " . tablename($this->table_tablezones) . " where weid = :weid AND id=:id LIMIT 1", array(':weid' => $weid, ':id' => $order['tablezonesid']));
            $content .= "桌台类型：{$tablezones['title']}<BR>";
        }
        if (!empty($order['tables'])) {
            $content .= '桌台信息:<B>' . $this->getTableName($order['tables']) . "</B><BR>";
        }

        if (!empty($order['remark'])) {
            $content .= '备注:' . $order['remark'] . "<BR>";
        }
        $content .= '门店地址:' . $store['address'] . "<BR>";
        $content .= '门店电话:' . $store['tel'] . "<BR>";

        $content2 = "-------------------------<BR>";
        $content2 .= "总数量:" . $order['totalnum'] . "   总价:" . number_format($order['totalprice'], 2) . "元<BR>";
        if ($order['dining_mode'] != 4 && !empty($order['meal_time'])) {
            $content2 .= '预定时间:' . $order['meal_time'] . "<BR>";
        }
        if (!empty($order['username'])) {
            $content2 .= '姓名:' . $order['username'] . "<BR>";
        }
        if (!empty($order['tel'])) {
            $content2 .= '手机:' . $order['tel'] . "<BR>";
        }
        if (!empty($order['address'])) {
            $content2 .= '地址:' . $order['address'] . "<BR>";
        }
        $content2 .= "-------------------------<BR>";

        $dining_mode = intval($order['dining_mode']);//1:店内2:外卖3:预定4:快餐
        foreach ($settings as $item => $value) {
            $loop_first = 0;
            if ($value['is_meal'] == 1 && $dining_mode == 1) {
                $loop_first = 1;
            }
            if ($value['is_delivery'] == 1 && $dining_mode == 2) {
                $loop_first = 1;
            }
            if ($value['is_reservation'] == 1 && $dining_mode == 3) {
                $loop_first = 1;
            }
            if ($value['is_snack'] == 1 && $dining_mode == 4) {
                $loop_first = 1;
            }
            if ($loop_first == 0) {
                continue;
            }

            $FEIE_IP = 'dzp.feieyun.com';
            $pos = strpos($value['print_usr'], '6');
            if ($pos == 2) {
                $FEIE_IP = 'api163.feieyun.com';
            }
            $pos = strpos($value['print_usr'], '7');
            if ($pos == 2) {
                $FEIE_IP = 'api174.feieyun.com';
            }
            if ($value['print_type'] == 1) {
                if ($order['ispay'] == 0) {
                    continue;
                }
            }

            $client = new HttpClient($FEIE_IP, FEIE_PORT);
            if ($order['status'] == -1) {
                $print_order_data = array(
                    'weid' => $weid,
                    'orderid' => $orderid,
                    'print_usr' => $value['print_usr'],
                    'print_status' => -1,
                    'dateline' => TIMESTAMP
                );
                pdo_insert($this->table_print_order, $print_order_data);
                $oid = pdo_insertid();

                $cancelcontent = '^订单已取消' . "\n";
                $cancelcontent .= '编号:' . $order['ordersn'];
                $feie_content = array(
                    'sn' => $value['print_usr'],
                    'printContent' => $cancelcontent,
                    'key' => $value['feyin_key'],
                    'times' => 1//打印次数
                );
                $result = $client->post(FEIE_HOSTNAME . '/printOrderAction', $feie_content);
                $_feiestatus = $result['responseCode'];
                pdo_update('weisrc_dish_print_order', array('print_status' => $_feiestatus), array('id' => $oid));
                return;
            }

            if (!empty($value['print_top'])) {
                $print_top = "<CB>" . $value['print_top'] . "</CB><BR>";
            }
            if (!empty($value['print_bottom'])) {
                $print_bottom = "<BR><C>" . $value['print_bottom'] . "</C>";
            }
            //商品
            if ($value['print_label'] == '0') {
                $goods = pdo_fetchall("SELECT * FROM " . tablename($this->table_goods) . "  WHERE id IN ('" . implode("','", array_keys($goodsid)) . "')");
            } else {
                $goods = pdo_fetchall("SELECT * FROM " . tablename($this->table_goods) . "  WHERE id IN ('" . implode("','", array_keys($goodsid)) . "') AND labelid IN(" . $value['print_label'] . ")");
            }
            if (empty($goods) && $order['dining_mode']!=3) {
                continue;
            }
            $order['goods'] = $goods;
            if ($goods) {
                $content1 = "菜单列表<BR>";
                $content1 .= "-------------------------<BR>";
            }

            if ($value['is_print_all'] == 1) {
                if ($value['type'] == 'feie') { //飞印
                    $print_order_data = array(
                        'weid' => $weid,
                        'orderid' => $orderid,
                        'print_usr' => $value['print_usr'],
                        'print_status' => -1,
                        'dateline' => TIMESTAMP
                    );
                    pdo_insert($this->table_print_order, $print_order_data);
                    $oid = pdo_insertid();
                }
                foreach ($order['goods'] as $v) {
                    $money = $v['marketprice'];
                    $content1 .= $v['title'] . ' ' . $goodsid[$v['id']]['total'] . $v['unitname'] . ' ' . number_format($money, 2) . "元\n";
                }
                if (!empty($value['qrcode_url']) && !empty($value['qrcode_status'])) {
                    $print_bottom .= "<QR>" . $value['qrcode_url'] . "</QR>";
                }

                $printContent = $print_top . $content . $content1 . $content2 . $print_bottom;

                $feie_content = array(
                    'sn' => $value['print_usr'],
                    'printContent' => $printContent,
                    'key' => $value['feyin_key'],
                    'times' => $value['print_nums']//打印次数
                );
                $result = $client->post(FEIE_HOSTNAME . '/printOrderAction', $feie_content);
                $_feiestatus = $result['responseCode'];

                pdo_update('weisrc_dish_print_order', array('print_status' => $_feiestatus), array('id' => $oid));
            } else { //分单
                $content = '订单编号:' . $order['ordersn'] . "<BR>";
//                $content .= '订单类型:' . $ordertype[$order['dining_mode']] . "<BR>";
//                $content .= '所属门店:' . $store['title'] . "<BR>";
//                $content .= '支付方式:' . $paytype[$order['paytype']] . "(" . $paystatus . ")<BR>";
                $content .= '下单日期:' . date('Y-m-d H:i:s', $order['dateline']) . "<BR>";
//                if ($order['dining_mode'] != 4 && !empty($order['meal_time'])) {
//                    $content .= '预定时间:' . $order['meal_time'] . "<BR>";
//                }
                if (!empty($order['tables'])) {
                    $content .= '<B>桌台信息:</B><DB>' . $this->getTableName($order['tables']) . "</DB><BR>";
                }
                if (!empty($order['remark'])) {
                    $content .= '<DB>备注:' . $order['remark'] . "</DB><BR>";
                }
//                if (!empty($order['username'])) {
//                    $content2 = '姓名:' . $order['username'] . "<BR>";
//                }
//                if (!empty($order['tel'])) {
//                    $content2 .= '手机:' . $order['tel'] . "<BR>";
//                }
//                if (!empty($order['address'])) {
//                    $content2 .= '地址:' . $order['address'] . "<BR>";
//                }
                foreach ($order['goods'] as $v) {
                    if ($value['type'] == 'feie') { //飞印
                        $print_order_data = array(
                            'weid' => $weid,
                            'orderid' => $orderid,
                            'print_usr' => $value['print_usr'],
                            'print_status' => -1,
                            'dateline' => TIMESTAMP
                        );
                        pdo_insert($this->table_print_order, $print_order_data);
                        $oid = pdo_insertid();
                    }
                    $content1 = '';
                    $content1 .= "------------------------------------------------<BR>";
                    $content1 .= '<B>名称:' . $v['title'] . "</B><BR>";
                    $content1 .= '<B>数量:' . $goodsid[$v['id']]['total'] . $v['unitname'] . "</B><BR>";
                    $content1 .= "------------------------------------------------<BR>";
                    $printContent = $print_top . $content . $content1 . $print_bottom;
                    $feie_content = array(
                        'sn' => $value['print_usr'],
                        'printContent' => $printContent,
                        'key' => $value['feyin_key'],
                        'times' => $value['print_nums']//打印次数
                    );

                    $result = $client->post(FEIE_HOSTNAME . '/printOrderAction', $feie_content);
                    $_feiestatus = $result['responseCode'];
                    pdo_update('weisrc_dish_print_order', array('print_status' => $_feiestatus), array('id' => $oid));
                }
            }
        }
    }
    //飞印
    public function feiyinSendFreeMessage($orderid = 0, $print_type = 0)
    {
        global $_W, $_GPC;
        $weid = $this->_weid;

        if ($orderid == 0)return -2;
        $order = pdo_fetch("SELECT * FROM " . tablename($this->table_order) . " WHERE  id =:id AND weid=:weid ORDER BY id DESC limit 1", array(':id' => $orderid, ':weid' => $weid));
        if (empty($order))return -3;
        $storeid = $order['storeid'];
        //打印机配置信息
        $settings = pdo_fetchall("SELECT * FROM " . tablename($this->table_print_setting) . " WHERE storeid = :storeid AND print_status=1 AND type='feiyin' ", array(':storeid' => $storeid));

        if ($settings == false) {
            return -4;
        }

        //商品id数组
        $paytype = array('0' => '线下付款', '1' => '余额支付', '2' => '微信支付', '3' => $order['dining_mode']==1?'餐后付款':'货到付款',
            '4' => '支付宝');
        $goodsid = pdo_fetchall("SELECT goodsid, total FROM " . tablename($this->table_order_goods) . " WHERE orderid = :orderid", array(':orderid' => $orderid), 'goodsid');

        $store = pdo_fetch("SELECT * FROM " . tablename($this->table_stores) . " WHERE  id =:id AND weid=:weid ORDER BY id DESC limit 1", array(':id' => $storeid, ':weid' => $weid));
        $ordertype = array(
            '1' => '堂点',
            '2' => '外卖',
            '3' => '预定',
            '4' => '快餐'
        );

        $paystatus = $order['ispay'] == 0 ? '未支付' : '已支付';
        $content = '订单编号:' . $order['ordersn'] . "\n";
        $content .= '订单类型:' . $ordertype[$order['dining_mode']] . "\n";
        $content .= '所属门店:' . $store['title'] . "\n";
        $content .= '支付方式:' . $paytype[$order['paytype']] . "(" . $paystatus . ")\n";
        $content .= '下单日期:' . date('Y-m-d H:i:s', $order['dateline']) . "\n";
        if ($order['dining_mode'] == 3) {
            $tablezones = pdo_fetch("SELECT * FROM " . tablename($this->table_tablezones) . " where weid = :weid AND id=:id LIMIT 1", array(':weid' => $weid, ':id' => $order['tablezonesid']));
            $content .= "桌台类型：{$tablezones['title']}\n";
        }
        if (!empty($order['tables'])) {
            $content .= '桌台信息:' . $this->getTableName($order['tables']) . "\n";
        }

        if (!empty($order['remark'])) {
            $content .= '备注:' . $order['remark'] . "\n";
        }
        $content .= '门店地址:' . $store['address'] . "\n";
        $content .= '门店电话:' . $store['tel'] . "\n";

        $content2 = "-------------------------\n";
        $content2 .= "总数量:" . $order['totalnum'] . "   总价:" . number_format($order['totalprice'], 2) . "元\n";
        if ($order['dining_mode'] != 4 && !empty($order['meal_time'])) {
            $content2 .= '预定时间:' . $order['meal_time'] . "\n";
        }
        if (!empty($order['username'])) {
            $content2 .= '姓名:' . $order['username'] . "\n";
        }
        if (!empty($order['tel'])) {
            $content2 .= '手机:' . $order['tel'] . "\n";
        }
        if (!empty($order['address'])) {
            $content2 .= '地址:' . $order['address'] . "\n";
        }
        $content2 .= "-------------------------\n";

        $dining_mode = intval($order['dining_mode']);//1:店内2:外卖3:预定4:快餐
        foreach ($settings as $item => $value) {
            $loop_first = 0;
            if ($value['is_meal'] == 1 && $dining_mode == 1) {
                $loop_first = 1;
            }
            if ($value['is_delivery'] == 1 && $dining_mode == 2) {
                $loop_first = 1;
            }
            if ($value['is_reservation'] == 1 && $dining_mode == 3) {
                $loop_first = 1;
            }
            if ($value['is_snack'] == 1 && $dining_mode == 4) {
                $loop_first = 1;
            }
            if ($loop_first == 0) {
                continue;
            }

            if ($value['print_type'] == 1) {
                if ($order['ispay'] == 0) {
                    continue;
                }
            }

            if (!empty($value['print_top'])) {
                $print_top = "" . $value['print_top'] . "\n";
            }
            if (!empty($value['print_bottom'])) {
                $print_bottom = "\n" . $value['print_bottom'] . "";
            }

            $this->member_code = $value['member_code'];
            $this->device_no = $value['print_usr'];
            $this->feyin_key = $value['feyin_key'];

            if ($order['status'] == -1) {
                $print_order_data = array(
                    'weid' => $weid,
                    'orderid' => $orderid,
                    'print_usr' => $value['print_usr'],
                    'print_status' => -1,
                    'dateline' => TIMESTAMP
                );
                pdo_insert($this->table_print_order, $print_order_data);
                $oid = pdo_insertid();
                $cancelcontent = '^订单已取消' . "\n";
                $cancelcontent .= '编号:' . $order['ordersn'];
                $freeMessage = array(
                    'memberCode' => $this->member_code,
                    'msgDetail' => $cancelcontent,
                    'deviceNo' => $this->device_no,
                    'msgNo' => $oid,
                );

                $feiyinstatus = $this->sendFreeMessage($freeMessage);
                pdo_update('weisrc_dish_print_order', array('print_status' => $feiyinstatus), array('id' => $oid));
                return;
            }

            //商品
            if ($value['print_label'] == '0') {
                $goods = pdo_fetchall("SELECT * FROM " . tablename($this->table_goods) . "  WHERE id IN ('" . implode("','", array_keys($goodsid)) . "')");
            } else {
                $goods = pdo_fetchall("SELECT * FROM " . tablename($this->table_goods) . "  WHERE id IN ('" . implode("','", array_keys($goodsid)) . "') AND labelid IN(" . $value['print_label'] . ")");
            }
            if (empty($goods) && $order['dining_mode']!=3) {
                continue;
            }
            $order['goods'] = $goods;
            if ($goods) {
                $content1 = "菜单列表\n";
                $content1 .= "-------------------------\n";
            }

            if ($value['is_print_all'] == 1) {
                if ($value['type'] == 'feiyin') { //飞印
                    $print_order_data = array(
                        'weid' => $weid,
                        'orderid' => $orderid,
                        'print_usr' => $value['print_usr'],
                        'print_status' => -1,
                        'dateline' => TIMESTAMP
                    );
                    pdo_insert($this->table_print_order, $print_order_data);
                    $oid = pdo_insertid();
                }

                foreach ($order['goods'] as $v) {
                    $money = $v['marketprice'];
                    $content1 .= $v['title'] . ' ' . $goodsid[$v['id']]['total'] . $v['unitname'] . ' ' . number_format($money, 2) . "元\n";
                }
                $msgDetail = $print_top . $content . $content1 . $content2 . $print_bottom;
                $msgNo = time() + 1;
                $freeMessage = array(
                    'memberCode' => $this->member_code,
                    'msgDetail' => $msgDetail,
                    'deviceNo' => $this->device_no,
                    'msgNo' => $oid,
                );
                $feiyinstatus = $this->sendFreeMessage($freeMessage);
                pdo_update('weisrc_dish_print_order', array('print_status' => $feiyinstatus), array('id' => $oid));
            } else {
                $content = '订单编号:' . $order['ordersn'] . "\n";
//                $content .= '订单类型:' . $ordertype[$order['dining_mode']] . "\n";
                $content .= '所属门店:' . $store['title'] . "\n";
                $content .= '支付方式:' . $paytype[$order['paytype']] . "(" . $paystatus . ")\n";
                $content .= '下单日期:' . date('Y-m-d H:i:s', $order['dateline']) . "\n";
//                if ($order['dining_mode'] != 4 && !empty($order['meal_time'])) {
//                    $content .= '预定时间:' . $order['meal_time'] . "\n";
//                }
                if (!empty($order['tables'])) {
                    $content .= '桌台信息:' . $this->getTableName($order['tables']) . "\n";
                }
                if (!empty($order['remark'])) {
                    $content .= '备注:' . $order['remark'] . "\n";
                }
//                if (!empty($order['username'])) {
//                    $content2 = '姓名:' . $order['username'] . "\n";
//                }
//                if (!empty($order['tel'])) {
//                    $content2 .= '手机:' . $order['tel'] . "\n";
//                }
//                if (!empty($order['address'])) {
//                    $content2 .= '地址:' . $order['address'] . "\n";
//                }
                foreach ($order['goods'] as $v) {
                    if ($value['type'] == 'feiyin') { //飞印
                        $print_order_data = array(
                            'weid' => $weid,
                            'orderid' => $orderid,
                            'print_usr' => $value['print_usr'],
                            'print_status' => -1,
                            'dateline' => TIMESTAMP
                        );
                        pdo_insert($this->table_print_order, $print_order_data);
                        $oid = pdo_insertid();
                    }
                    $content1 = '';
                    $content1 .= "-------------------------\n";
                    $content1 .= '名称:' . $v['title'] . "\n";
                    $content1 .= '数量:' . $goodsid[$v['id']]['total'] . $v['unitname'] . "\n";
                    $content1 .= "-------------------------\n";

                    $msgDetail = $print_top . $content . $content1 . $content2 . $print_bottom;
                    $msgNo = time() + 1;
                    $freeMessage = array(
                        'memberCode' => $this->member_code,
                        'msgDetail' => $msgDetail,
                        'deviceNo' => $this->device_no,
                        'msgNo' => $oid,
                    );
                    $feiyinstatus = $this->sendFreeMessage($freeMessage);
                    pdo_update('weisrc_dish_print_order', array('print_status' => $feiyinstatus), array('id' => $oid));
                }
            }
        }
        return $msgNo;
    }

    public function getGoodsTitle($str1, $len, $stradd = "")
    {
        $i = 0;
        $str2 = "^B2";
        if ($len % 2 == 1) $len = $len + 1;
        $len1 = strlen($str1);
        for ($i = 0; $i < $len1 / $len; $i++) {
            $str2 .= '^B2' . substr($str1, $len * $i, $len) . $stradd;
            $str1 = substr($str1, $len * $i, $len1 - $len * $i);
        }
        return $str2;
    }

    //用户打印机处理订单
    private function feiyinformat($string, $length = 0, $isleft = true)
    {
        $substr = '';
        if ($length == 0 || $string == '') {
            return $string;
        }
        if ($this->print_strlen($string) > $length) {
            for ($i = 0; $i < $length; $i++) {
                $substr = $substr . "  ";
            }
            $string = $string . $substr;
        } else {
            for ($i = $this->print_strlen($string); $i < $length; $i++) {
                $substr = $substr . " ";
            }
            $string = $isleft ? ($string . $substr) : ($substr . $string);
        }
        return $string;
    }

    /**
     * @param string $l
     * @param string $r
     * @return string
     */
    public function formatstr($l = '', $r = '')
    {
        $nbsp = '                              ';
        $llen = $this->print_strlen($l);
        $rlen = $this->print_strlen($r);
        if ($l && $r) {
            $lr = $llen + $rlen;
            $nl = $this->print_strlen($nbsp);
            if ($lr >= $nl) {
                $strtxt = $l . "\r\n" . $this->formatstr(null, $r);
            } else {
                $strtxt = $l . substr($nbsp, $lr) . $r;
            }
        } elseif ($r) {
            $strtxt = substr($nbsp, $rlen) . $r;
        } else {
            $strtxt = $l;
        }
        return $strtxt;
    }

    /**
     * PHP获取字符串中英文混合长度
     * @param $str        字符串
     * @param string $charset 编码
     * @return int 返回长度，1中文=2位(utf-8为3位)，1英文=1位
     */
    private function print_strlen($str, $charset = '')
    {
        global $_W;
        if (empty($charset)) {
            $charset = $_W['charset'];
        }
        if (strtolower($charset) == 'gbk') {
            $charset = 'gbk';
            $ci = 2;
        } else {
            $charset = 'utf-8';
            $ci = 3;
        }
        if (strtolower($charset) == 'utf-8') $str = iconv('utf-8', 'GBK//IGNORE', $str);
        $num = strlen($str);
        $cnNum = 0;
        for ($i = 0; $i < $num; $i++) {
            if (ord(substr($str, $i + 1, 1)) > 127) {
                $cnNum++;
                $i++;
            }
        }
        $enNum = $num - ($cnNum * $ci);
        $number = $enNum + $cnNum * $ci;
        return ceil($number);
    }

    public function sendQueueNotice($oid, $status = 1)
    {
        global $_W, $_GPC;
        $weid = $this->_weid;
        $from_user = $this->_fromuser;

        $setting = pdo_fetch("select * from " . tablename($this->table_setting) . " WHERE weid =:weid LIMIT 1", array(':weid' => $weid));
        $order = pdo_fetch("select * from " . tablename($this->table_queue_order) . " WHERE id =:id LIMIT 1", array(':id' => $oid));
        $store = pdo_fetch("select * from " . tablename($this->table_stores) . " WHERE id =:id LIMIT 1", array(':id' => $order['storeid']));
        $keyword1 = $order['num'];
        $keyword2 = date("Y-m-d H:i", $order['dateline']);
        $url = $_W['siteroot'] . 'app' . str_replace('./', '/', $this->createMobileUrl('queue', array('storeid' => $order['storeid']), true));
        $wait_count = pdo_fetchcolumn("SELECT COUNT(1) FROM " . tablename($this->table_queue_order) . " WHERE status=1 AND storeid=:storeid AND id<:id AND queueid=:queueid ORDER BY id DESC", array(':id' => $oid, ':storeid' => $order['storeid'], ':queueid' => $order['queueid']));
        $queueStatus = array(
            '1' => '排队中',
            '2' => '已接受',
            '-1' => '已取消',
            '3' => '已过号'
        );

        if (!empty($setting['tplnewqueue']) && $setting['istplnotice'] == 1) {
            $templateid = $setting['tplnewqueue'];
            if ($setting['tpltype'] == 1) {
                if ($status == 1) { //排队中
                    $first = "排号提醒：编号{$keyword1}已成功领号，您可以点击本消息提前点菜，节约等待时间哦";
                    $remark = "门店名称：{$store['title']}";
                    $remark .= "\n排队号码：" . $this->getQueueName($order['queueid']) . " " . $order['num'];
                    $remark .= "\n前面等待：" . intval($wait_count);
                    $remark .= "\n排队状态：排队中";
                } else if ($status == 2) { //排队提醒
                    $first = "排号提醒：还需等待{$wait_count}桌";
                    $remark = "门店名称：{$store['title']}";
                    $remark .= "\n排队号码：" . $this->getQueueName($order['queueid']) . " " . $order['num'];
                    $remark .= "\n前面等待：" . intval($wait_count) . "桌";
                    $remark .= "\n排队状态：" . $queueStatus[$order['status']];
                } else if ($status == 3) { //取消提醒
                    $first = "排号取消提醒：编号" . $order['num'] . "已取消";
                    $remark = "您在{$store['title']}的排队状态更新为已取消，如有疑问，请联系我们工作人员";
                    $remark .= "\n排队号码：" . $this->getQueueName($order['queueid']) . " " . $order['num'];
                    $remark .= "\n排队状态：已取消";
                }

                $content = array(
                    'first' => array(
                        'value' => $first,
                        'color' => '#a6a6a9'
                    ),
                    'keyword1' => array(
                        'value' => $keyword1,
                        'color' => '#a6a6a9'
                    ),
                    'keyword2' => array(
                        'value' => $keyword2,
                        'color' => '#a6a6a9'
                    ),
                    'remark' => array(
                        'value' => $remark,
                        'color' => '#a6a6a9'
                    ),
                );
            } else {
                $keyword3 = intval($wait_count);
                if ($status == 1) { //排队中

                    $first = "排号提醒：编号{$keyword1}已成功领号，您可以点击本消息提前点菜，节约等待时间哦";
                    $remark = "门店名称：{$store['title']}";
                    $remark .= "\n排队号码：" . $this->getQueueName($order['queueid']) . " " . $order['num'];
                    $remark .= "\n排队状态：排队中";
                } else if ($status == 2) { //排队提醒
                    $first = "排号提醒：还需等待{$wait_count}桌";
                    $remark = "门店名称：{$store['title']}";
                    $remark .= "\n排队号码：" . $this->getQueueName($order['queueid']) . " " . $order['num'];
                    $remark .= "\n排队状态：" . $queueStatus[$order['status']];
                } else if ($status == 3) { //取消提醒
                    $first = "排号取消提醒：编号" . $order['num'] . "已取消";
                    $remark = "您在{$store['title']}的排队状态更新为已取消，如有疑问，请联系我们工作人员";
                    $remark .= "\n排队号码：" . $this->getQueueName($order['queueid']) . " " . $order['num'];
                    $remark .= "\n排队状态：已取消";
                }

                $content = array(
                    'first' => array(
                        'value' => $first,
                        'color' => '#a6a6a9'
                    ),
                    'keyword1' => array(
                        'value' => $keyword1,
                        'color' => '#a6a6a9'
                    ),
                    'keyword2' => array(
                        'value' => $keyword2,
                        'color' => '#a6a6a9'
                    ),
                    'keyword3' => array(
                        'value' => $keyword3,
                        'color' => '#a6a6a9'
                    ),
                    'remark' => array(
                        'value' => $remark,
                        'color' => '#a6a6a9'
                    ),
                );
            }

            pdo_update($this->table_queue_order, array('isnotify' => 1), array('id' => $oid));
            load()->model('account');
            $access_token = WeAccount::token();
            $templateMessage = new templateMessage();
            $templateMessage->send_template_message($order['from_user'], $templateid, $content, $access_token, $url);
        } else {
            if ($status == 1) { //排队中
                $content = '排号提醒：编号' . $keyword1 . '已成功领号，您可以<a href=\"' . $url . '\">点击本消息</a>提前点菜，节约等待时间哦';
                $content .= "\n当前排号：{$keyword1}";
                $content .= "\n取号时间：{$keyword2}";
                $content .= "\n门店名称：{$store['title']}";
                $content .= "\n排队号码：" . $this->getQueueName($order['queueid']) . " " . $order['num'];
                $content .= "\n前面等待：" . intval($wait_count);
                $content .= "\n排队状态：排队中";
            } else if ($status == 2) { //排队提醒
                $content = "排号提醒：还需等待{$wait_count}桌";
                $content .= "\n当前排号：{$keyword1}";
                $content .= "\n取号时间：{$keyword2}";
                $content .= "\n门店名称：{$store['title']}";
                $content .= "\n排队号码：" . $this->getQueueName($order['queueid']) . " " . $order['num'];
                $content .= "\n前面等待：" . intval($wait_count) . "桌";
                $content .= "\n排队状态：" . $queueStatus[$order['status']];
            } else if ($status == 3) { //取消提醒
                $content = "排号取消提醒：编号" . $order['num'] . "已取消";
                $content .= "\n当前排号：{$keyword1}";
                $content .= "\n取号时间：{$keyword2}";
                $content .= "\n您在{$store['title']}的排队状态更新为已取消，如果疑问，请联系我们工作人员";
                $content .= "\n排队号码：" . $this->getQueueName($order['queueid']) . " " . $order['num'];
                $content .= "\n排队状态：已取消";
            }
            $this->sendText($order['from_user'], $content);
        }
    }

    public function sendAdminQueueNotice($oid, $from_user, $setting)
    {
        global $_W, $_GPC;
        $weid = $this->_weid;

        $order = pdo_fetch("select * from " . tablename($this->table_queue_order) . " WHERE id =:id LIMIT 1", array(':id' => $oid));
        $store = pdo_fetch("select * from " . tablename($this->table_stores) . " WHERE id =:id LIMIT 1", array(':id' => $order['storeid']));
        $keyword1 = $order['num'];
        $keyword2 = date("Y-m-d H:i", $order['dateline']);
        $url = '';
        $wait_count = pdo_fetchcolumn("SELECT COUNT(1) FROM " . tablename($this->table_queue_order) . " WHERE status=1 AND storeid=:storeid AND queueid=:queueid ORDER BY id DESC", array(':storeid' => $order['storeid'], ':queueid' => $order['queueid']));

        if (!empty($setting['tplnewqueue']) && $setting['istplnotice'] == 1 && $setting['is_notice'] == 1 && !empty($from_user)) {
            $templateid = $setting['tplnewqueue'];

            $first = '排号提醒：有新的排号，编号' . $keyword1;

            if ($setting['tpltype'] == 1) {
                $remark = "门店名称：{$store['title']}";
                $remark .= "\n排队号码：" . $this->getQueueName($order['queueid']) . " " . $order['num'];
                $remark .= "\n排队等待：" . intval($wait_count) . '队';

                $content = array(
                    'first' => array(
                        'value' => $first,
                        'color' => '#a6a6a9'
                    ),
                    'keyword1' => array(
                        'value' => $keyword1,
                        'color' => '#a6a6a9'
                    ),
                    'keyword2' => array(
                        'value' => $keyword2,
                        'color' => '#a6a6a9'
                    ),
                    'remark' => array(
                        'value' => $remark,
                        'color' => '#a6a6a9'
                    ),
                );
            } else {
                $remark = "门店名称：{$store['title']}";
                $remark .= "\n排队号码：" . $this->getQueueName($order['queueid']) . " " . $order['num'];

                $keyword3 = intval($wait_count);

                $content = array(
                    'first' => array(
                        'value' => $first,
                        'color' => '#a6a6a9'
                    ),
                    'keyword1' => array(
                        'value' => $keyword1,
                        'color' => '#a6a6a9'
                    ),
                    'keyword2' => array(
                        'value' => $keyword2,
                        'color' => '#a6a6a9'
                    ),
                    'keyword3' => array(
                        'value' => $keyword3,
                        'color' => '#a6a6a9'
                    ),
                    'remark' => array(
                        'value' => $remark,
                        'color' => '#a6a6a9'
                    )
                );
            }

            pdo_update($this->table_queue_order, array('isnotify' => 1), array('id' => $oid));
            load()->model('account');
            $access_token = WeAccount::token();
            $templateMessage = new templateMessage();
            $templateMessage->send_template_message($order['from_user'], $templateid, $content, $access_token, $url);
        } else {
            if (!empty($setting['tpluser'])) { //排队中
                $content = '排号提醒：有新的排号，编号' . $keyword1;
                $content .= "\n当前排号：{$keyword1}";
                $content .= "\n取号时间：{$keyword2}";
                $content .= "\n门店名称：{$store['title']}";
                $content .= "\n排队号码：" . $this->getQueueName($order['queueid']) . " " . $order['num'];
                $content .= "\n排队等待：" . intval($wait_count) . '队';
            }
            $this->sendText($from_user, $content);
        }
    }

    public function sendOrderSms($order)
    {
        global $_W, $_GPC;
        $weid = $order['weid'];

        //发送短信提醒
        $smsSetting = pdo_fetch("SELECT * FROM " . tablename($this->table_setting) . " WHERE weid=:weid LIMIT 1", array(':weid' => $weid));
        $sendInfo = array();
        if (!empty($smsSetting)) {
            if ($smsSetting['sms_enable'] == 1 && !empty($order['tel'])) {
                //模板
                $smsSetting['sms_business_tpl'] = '您的订单：[sn]，收货人：[name] 电话：[tel]，已经成功提交。感谢您的购买！';
                //订单号
                $smsSetting['sms_business_tpl'] = str_replace('[sn]', $order['ordersn'], $smsSetting['sms_business_tpl']);
                $smsSetting['sms_business_tpl'] = str_replace('[name]', $order['username'], $smsSetting['sms_business_tpl']);
                $smsSetting['sms_business_tpl'] = str_replace('[tel]', $order['tel'], $smsSetting['sms_business_tpl']);

                $sendInfo['username'] = $smsSetting['sms_username'];
                $sendInfo['pwd'] = $smsSetting['sms_pwd'];
                $sendInfo['mobile'] = $order['tel'];
                $sendInfo['content'] = $smsSetting['sms_business_tpl'];
                //debug

                $return_result_code = $this->_sendSms($sendInfo);
                $smsStatus = $this->sms_status[$return_result_code];
            }
        }
    }

    public function sendAdminOrderSms($mobile, $order)
    {
        global $_W, $_GPC;
        $weid = $order['weid'];

        //发送短信提醒
        $smsSetting = pdo_fetch("SELECT * FROM " . tablename($this->table_setting) . " WHERE weid=:weid LIMIT 1", array(':weid' => $weid));
        $sendInfo = array();
        if (!empty($smsSetting)) {
            if ($smsSetting['sms_enable'] == 1 && !empty($mobile)) {
                $smsSetting['sms_business_tpl'] = '您有新的订单：[sn]，收货人：[name]，电话：[tel]，请及时确认订单！';
                $smsSetting['sms_business_tpl'] = str_replace('[sn]', $order['ordersn'], $smsSetting['sms_business_tpl']);
                $smsSetting['sms_business_tpl'] = str_replace('[name]', $order['username'], $smsSetting['sms_business_tpl']);
                $smsSetting['sms_business_tpl'] = str_replace('[tel]', $order['tel'], $smsSetting['sms_business_tpl']);

                $sendInfo['username'] = $smsSetting['sms_username'];
                $sendInfo['pwd'] = $smsSetting['sms_pwd'];
                $sendInfo['mobile'] = $mobile;
                $sendInfo['content'] = $smsSetting['sms_business_tpl'];
                //debug

                $return_result_code = $this->_sendSms($sendInfo);
                $smsStatus = $this->sms_status[$return_result_code];
            }
            return $smsStatus;
        }
    }

    public function sendAdminOrderEmail($toemail, $order, $store, $goods_str)
    {
        $firstArr = array(
            '-1' => '已经取消',
            '0' => '已经提交',
            '1' => '已经确认',
            '2' => '已并台',
            '3' => '已经完成'
        );

        $orderStatus = array(
            '-1' => '已取消',
            '0' => '待处理',
            '1' => '已确认',
            '2' => '已并台',
            '3' => '已完成'
        );
        $paytype = array(
            '0' => '现金付款',
            '1' => '余额支付',
            '2' => '微信支付',
            '3' => '现金付款',
            '4' => '支付宝'
        );
        $paystatus = array(
            '0' => '未支付',
            '1' => '已支付'
        );

        //发送邮件提醒
        $emailSetting = pdo_fetch("SELECT * FROM " . tablename($this->table_setting) . " WHERE weid=:weid LIMIT 1", array(':weid' => $order['weid']));

        $keyword1 = $order['ordersn'];
        $keyword2 = $orderStatus[$order['status']];
        $keyword3 = date("Y-m-d H:i", $order['dateline']);

        $email_tpl = "
        您的订单{$order['ordersn']}{$firstArr[$order['status']]}<br/>
        订单号：{$keyword1}<br/>
        订单状态：{$keyword2}<br/>
        时间：{$keyword3}<br/>
        门店名称：{$store['title']}<br/>
        支付方式：{$paytype[$order['paytype']]}<br/>
        支付状态：{$paystatus[$order['ispay']]}<br/>
        ";
        if ($order['dining_mode'] == 3) {
            $email_tpl .= "预定人信息：{$order['username']}－{$order['tel']}<br/>";
            $email_tpl .= "预定时间：{$order['meal_time']}<br/>";
        } else {
            $email_tpl .= "联系方式：{$order['username']}－{$order['tel']}<br/>";
        }
        if ($order['dining_mode'] == 1) {
            $tablename = $this->getTableName($order['tables']);
            $email_tpl .= "桌台信息：{$tablename}<br/>";
        }
        if ($order['dining_mode'] == 2) {
            if (!empty($order['address'])) {
                $email_tpl .= "配送地址：{$order['address']}<br/>";
            }
            if (!empty($order['meal_time'])) {
                $email_tpl .= "配送时间：{$order['meal_time']}<br/>";
            }
        }
        $email_tpl .= "菜单：{$goods_str}<br/>";
        $email_tpl .= "备注：{$order['remark']}<br/>";
        $email_tpl .= "应收合计：{$order['totalprice']}";

        if (!empty($emailSetting) && !empty($emailSetting['email'])) {
            if ($emailSetting['email_host'] == 'smtp.qq.com' || $emailSetting['email_host'] == 'smtp.gmail.com') {
                $secure = 'ssl';
                $port = '465';
            } else {
                $secure = 'tls';
                $port = '25';
            }

            $mail_config = array();
            $mail_config['host'] = $emailSetting['email_host'];
            $mail_config['secure'] = $secure;
            $mail_config['port'] = $port;
            $mail_config['username'] = $emailSetting['email_user'];
            $mail_config['sendmail'] = $emailSetting['email_send'];
            $mail_config['password'] = $emailSetting['email_pwd'];
            $mail_config['mailaddress'] = $toemail;
            $mail_config['subject'] = '订单提醒';
            $mail_config['body'] = $email_tpl;
            $result = $this->sendmail($mail_config);
        }
    }

    public function sendOrderNotice($order, $store, $setting)
    {
        global $_W, $_GPC;
        $weid = $this->_weid;

        $firstArr = array(
            '-1' => '已经取消',
            '0' => '已经提交',
            '1' => '已经确认',
            '2' => '已并台',
            '3' => '已经完成'
        );

        $orderStatus = array(
            '-1' => '已取消',
            '0' => '待处理',
            '1' => '已确认',
            '2' => '已并台',
            '3' => '已完成'
        );
        $paytype = array(
            '0' => '现金付款',
            '1' => '余额支付',
            '2' => '微信支付',
            '3' => '现金付款',
            '4' => '支付宝'
        );
        $paystatus = array(
            '0' => '未支付',
            '1' => '已支付'
        );

        $url = $_W['siteroot'] . 'app' . str_replace('./', '/', $this->createMobileUrl('orderdetail', array('orderid' => $order['id']), true));
        $keyword1 = $order['ordersn'];
        $keyword2 = $orderStatus[$order['status']];
        $keyword3 = date("Y-m-d H:i", $order['dateline']);

        if (!empty($setting['tplneworder']) && $setting['istplnotice'] == 1) {
            $templateid = $setting['tplneworder'];
            $first = "您的订单{$order['ordersn']}{$firstArr[$order['status']]}";
            $remark = "门店名称：{$store['title']}";
            $remark .= "\n支付方式：{$paytype[$order['paytype']]}";
            $remark .= "\n支付状态：{$paystatus[$order['ispay']]}";
            if ($order['dining_mode'] == 3) {
                if ($order['dining_mode'] == 3) {
                    $tablezones = pdo_fetch("SELECT * FROM " . tablename($this->table_tablezones) . " where weid = :weid AND id=:id LIMIT 1", array(':weid' => $weid, ':id' => $order['tablezonesid']));
                }
                $remark .= "\n预定人信息：{$order['username']}－{$order['tel']}";
                $remark .= "\n桌台类型：{$tablezones['title']}";
                $remark .= "\n预定时间：{$order['meal_time']}";
            } else {
                $remark .= "\n联系方式：{$order['username']}－{$order['tel']}";
            }
            if ($order['dining_mode'] == 1) {
                $tablename = $this->getTableName($order['tables']);
                $remark .= "\n桌台信息：{$tablename}";
            }
            if ($order['dining_mode'] == 2) {
                if (!empty($order['address'])) {
                    $remark .= "\n配送地址：{$order['address']}";
                }
                if (!empty($order['meal_time'])) {
                    $remark .= "\n配送时间：{$order['meal_time']}";
                }
            }
            if (!empty($order['remark'])) {
                $remark .= "\n备注：{$order['remark']}";
            }
            if (!empty($order['reply'])) {
                $remark .= "\n商家回复：{$order['reply']}";
            }

            $remark .= "\n应收合计：{$order['totalprice']}元";
            if ($order['credit'] > 0) {
                $remark .= "\n奖励积分：{$order['credit']}";
            }
            if ($setting['tpltype'] == 1) {
                $content = array(
                    'first' => array(
                        'value' => $first,
                        'color' => '#a6a6a9'
                    ),
                    'keyword1' => array(
                        'value' => $keyword1,
                        'color' => '#a6a6a9'
                    ),
                    'keyword2' => array(
                        'value' => $keyword2,
                        'color' => '#a6a6a9'
                    ),
                    'keyword3' => array(
                        'value' => $keyword3,
                        'color' => '#a6a6a9'
                    ),
                    'remark' => array(
                        'value' => $remark,
                        'color' => '#a6a6a9'
                    ),
                );
            } else {
                $remark = "订单状态：" . $keyword2 . "\n" . $remark;
                $content = array(
                    'first' => array(
                        'value' => $first,
                        'color' => '#a6a6a9'
                    ),
                    'keyword1' => array(
                        'value' => $keyword1,
                        'color' => '#a6a6a9'
                    ),
                    'keyword2' => array(
                        'value' => $keyword3,
                        'color' => '#a6a6a9'
                    ),
                    'remark' => array(
                        'value' => $remark,
                        'color' => '#a6a6a9'
                    )
                );
            }

            load()->model('account');
            $access_token = WeAccount::token();
            $templateMessage = new templateMessage();
            $templateMessage->send_template_message($order['from_user'], $templateid, $content, $access_token, $url);
        } else {
            $content = "您的订单{$order['ordersn']}{$firstArr[$order['status']]}";
            $content .= "\n订单号：{$keyword1}";
            $content .= "\n订单状态：{$keyword2}";
            $content .= "\n时间：{$keyword3}";
            $content .= "\n门店名称：{$store['title']}";
            $content .= "\n支付方式：{$paytype[$order['paytype']]}";
            $content .= "\n支付状态：{$paystatus[$order['ispay']]}";

            if ($order['dining_mode'] == 3) {
                if ($order['dining_mode'] == 3) {
                    $tablezones = pdo_fetch("SELECT * FROM " . tablename($this->table_tablezones) . " where weid = :weid AND id=:id LIMIT 1", array(':weid' => $weid, ':id' => $order['tablezonesid']));
                }
                $content .= "\n预定人信息：{$order['username']}－{$order['tel']}";
                $content .= "\n桌台类型：{$tablezones['title']}";
                $content .= "\n预定时间：{$order['meal_time']}";
            } else {
                $content .= "\n联系方式：{$order['username']}－{$order['tel']}";
            }
            if ($order['dining_mode'] == 1) {
                $tablename = $this->getTableName($order['tables']);
                $content .= "\n桌台信息：{$tablename}";
            }
            if ($order['dining_mode'] == 2) {
                if (!empty($order['address'])) {
                    $content .= "\n配送地址：{$order['address']}";
                }
                if (!empty($order['meal_time'])) {
                    $content .= "\n配送时间：{$order['meal_time']}";
                }
            }
            if (!empty($order['remark'])) {
                $content .= "\n备注：{$order['remark']}";
            }
            if (!empty($order['reply'])) {
                $content .= "\n商家回复：{$order['reply']}";
            }

            $content .= "\n应收合计：{$order['totalprice']}元";
            if ($order['credit'] > 0) {
                $content .= "\n奖励积分：{$order['credit']}";
            }
            $this->sendText($order['from_user'], $content);
        }
    }

    public function addTplLog($order, $from_user, $content, $result)
    {
        global $_W, $_GPC;
        $insert = array(
            'weid' => $order['weid'],
            'from_user' => $from_user,
            'storeid' => $order['storeid'],
            'orderid' => $order['id'],
            'ordersn' => $order['ordersn'],
            'content' => $content,
            'result' => $result,
            'dateline' => TIMESTAMP
        );
        pdo_insert($this->table_tpl_log, $insert);
    }

    public function sendAdminOrderNotice($oid, $from_user, $setting)
    {
        global $_W, $_GPC;
        $weid = $this->_weid;

        $orderStatus = array(
            '-1' => '已取消',
            '0' => '待处理',
            '1' => '已确认',
            '2' => '已并台',
            '3' => '已完成'
        );
        $paytype = array(
            '0' => '现金付款',
            '1' => '余额支付',
            '2' => '微信支付',
            '3' => '现金付款',
            '4' => '支付宝'
        );
        $ordertype = array(
            '1' => '堂点',
            '2' => '外卖',
            '3' => '预定',
            '4' => '快餐'
        );
        $paystatus = array(
            '0' => '未支付',
            '1' => '已支付'
        );

        $order = pdo_fetch("select * from " . tablename($this->table_order) . " WHERE id =:id LIMIT 1", array(':id' => $oid));
        $store = pdo_fetch("select * from " . tablename($this->table_stores) . " WHERE id =:id LIMIT 1", array(':id' => $order['storeid']));
        $url = $_W['siteroot'] . 'app/' . $this->createMobileUrl('adminorderdetail', array(), true) . "&orderid=" . $oid;
        $keyword1 = $order['ordersn'];
        $keyword2 = $orderStatus[$order['status']];
        $keyword3 = date("Y-m-d H:i", $order['dateline']);

        if (!empty($setting['tplneworder']) && $setting['istplnotice'] == 1 && !empty($from_user)) {
            $templateid = $setting['tplneworder'];
            $first = "您有新的订单";
            $remark = "门店名称：{$store['title']}";
            if ($order['dining_mode'] == 1) {
                $tablename = $this->getTableName($order['tables']);
                $remark .= "\n桌台信息：{$tablename}";
            }
            $remark .= "\n订单类型：{$ordertype[$order['dining_mode']]}";
            $remark .= "\n支付方式：{$paytype[$order['paytype']]}";
            $remark .= "\n支付状态：{$paystatus[$order['ispay']]}";

            $goods = pdo_fetchall("SELECT a.*,b.title,b.unitname FROM " . tablename($this->table_order_goods) . " as a left join  " . tablename($this->table_goods) . " as b on a.goodsid=b.id WHERE a.weid = :weid and a.orderid=:orderid", array(':weid' => $weid, ':orderid' => $oid));
            if (!empty($goods)) {
                $remark .= "\n商品名称   单价 数量";
                $remark .= "\n－－－－－－－－－－－－－－－－";
                foreach ($goods as $key => $value) {
                    $remark .= "\n{$value['title']} {$value['price']}元 {$value['total']}{$value['unitname']}";
                }
            }

            if ($order['dining_mode'] == 3) {
                if ($order['dining_mode'] == 3) {
                    $tablezones = pdo_fetch("SELECT * FROM " . tablename($this->table_tablezones) . " where weid = :weid AND id=:id LIMIT 1", array(':weid' => $weid, ':id' => $order['tablezonesid']));
                }
                $remark .= "\n预定人信息：{$order['username']}－{$order['tel']}";
                $remark .= "\n桌台类型：{$tablezones['title']}";
                $remark .= "\n预定时间：{$order['meal_time']}";
            } else {
                $remark .= "\n联系方式：{$order['username']}－{$order['tel']}";
            }
            if ($order['dining_mode'] == 2) {
                if (!empty($order['address'])) {
                    $remark .= "\n配送地址：{$order['address']}";
                }
                if (!empty($order['meal_time'])) {
                    $remark .= "\n配送时间：{$order['meal_time']}";
                }
            }
            $remark .= "\n备注：{$order['remark']}";
            $remark .= "\n应收合计：{$order['totalprice']}元";

            if ($setting['tpltype'] == 1) {
                $content = array(
                    'first' => array(
                        'value' => $first,
                        'color' => '#a6a6a9'
                    ),
                    'keyword1' => array(
                        'value' => $keyword1,
                        'color' => '#a6a6a9'
                    ),
                    'keyword2' => array(
                        'value' => $keyword2,
                        'color' => '#a6a6a9'
                    ),
                    'keyword3' => array(
                        'value' => $keyword3,
                        'color' => '#a6a6a9'
                    ),
                    'remark' => array(
                        'value' => $remark,
                        'color' => '#a6a6a9'
                    )
                );
            } else {
                $remark = "订单状态：" . $keyword2 . "\n" . $remark;
                $content = array(
                    'first' => array(
                        'value' => $first,
                        'color' => '#a6a6a9'
                    ),
                    'keyword1' => array(
                        'value' => $keyword1,
                        'color' => '#a6a6a9'
                    ),
                    'keyword2' => array(
                        'value' => $keyword3,
                        'color' => '#a6a6a9'
                    ),
                    'remark' => array(
                        'value' => $remark,
                        'color' => '#a6a6a9'
                    )
                );
            }

            load()->model('account');
            $access_token = WeAccount::token();
            $templateMessage = new templateMessage();
            $result = $templateMessage->send_template_message($from_user, $templateid, $content, $access_token, $url);
            $result = $result['errmsg'] == 'ok' ? '发送成功' : $result['errmsg'];
            $this->addTplLog($order, $from_user, '管理员订单通知', $result);
        } else {
            $content = "您有新的订单";
            $content .= "\n订单类型：{$ordertype[$order['dining_mode']]}";
            $content .= "\n订单号：{$keyword1}";
            $content .= "\n订单状态：{$keyword2}";
            $content .= "\n时间：{$keyword3}";
            $content .= "\n门店名称：{$store['title']}";
            if ($order['dining_mode'] == 1) {
                $tablename = $this->getTableName($order['tables']);
                $content .= "\n桌台信息：{$tablename}";
            }
            $content .= "\n支付方式：{$paytype[$order['paytype']]}";
            $content .= "\n支付状态：{$paystatus[$order['ispay']]}";
            $goods = pdo_fetchall("SELECT a.*,b.title,b.unitname FROM " . tablename($this->table_order_goods) . " as a left join  " . tablename($this->table_goods) . " as b on a.goodsid=b.id WHERE a.weid = :weid and a.orderid=:orderid", array(':weid' => $weid, ':orderid' => $oid));
            if (!empty($goods)) {
                $content .= "\n商品名称   单价 数量";
                $content .= "\n－－－－－－－－－－－－－－－－";
                foreach ($goods as $key => $value) {
                    $content .= "\n{$value['title']} {$value['price']} {$value['total']}{$value['unitname']}";
                }
            }
            if ($order['dining_mode'] == 3) {
                if ($order['dining_mode'] == 3) {
                    $tablezones = pdo_fetch("SELECT * FROM " . tablename($this->table_tablezones) . " where weid = :weid AND id=:id LIMIT 1", array(':weid' => $weid, ':id' => $order['tablezonesid']));
                }
                $content .= "\n预定人信息：{$order['username']}－{$order['tel']}";
                $content .= "\n桌台类型：{$tablezones['title']}";
                $content .= "\n预定时间：{$order['meal_time']}";
            } else {
                $content .= "\n联系方式：{$order['username']}－{$order['tel']}";
            }
            if ($order['dining_mode'] == 2) {
                if (!empty($order['address'])) {
                    $content .= "\n配送地址：{$order['address']}";
                }
                if (!empty($order['meal_time'])) {
                    $content .= "\n配送时间：{$order['meal_time']}";
                }
            }
            $content .= "\n备注：{$order['remark']}";
            $content .= "\n应收合计：{$order['totalprice']}元";
            if (!empty($from_user)) {
                $this->sendText($from_user, $content);
            }
        }
    }

    public function getNewSncode($weid, $sncode)
    {
        global $_W, $_GPC;
        $sn = pdo_fetch("SELECT sncode FROM " . tablename($this->table_sncode) . " WHERE weid = :weid and sncode = :sn ORDER BY `id` DESC limit 1", array(':weid' => $weid, ':sn' => $sncode));
        if (!empty($sn)) {
            $sncode = 'A00' . random(11, 1);
            $this->getNewSncode($weid, $sncode);
        }
        return $sncode;
    }

    public function doMobileOrderlist()
    {
        $url = $this->createMobileUrl('order', array(), true);
        die('<script>location.href = "' . $url . '";</script>');
    }

    //取得购物车中的商品
    public function getDishCountInCart($storeid)
    {
        global $_GPC, $_W;
        $weid = $this->_weid;
        $from_user = $this->_fromuser;

        $dishlist = pdo_fetchall("SELECT * FROM " . tablename($this->table_cart) . " WHERE  storeid=:storeid AND from_user=:from_user AND weid=:weid", array(':from_user' => $from_user, ':weid' => $weid, ':storeid' => $storeid));
        foreach ($dishlist as $key => $value) {
            $arr[$value['goodsid']] = $value['total'];
        }
        return $arr;
    }

    public function doMobilePay()
    {
        global $_W, $_GPC;
        //查当前订单信息
        if (IMS_VERSION == '0.8') {
            load()->classs('coupon');
            $coupon_api = new coupon($_W['acid']);
            $is_coupon_supported = $coupon_api->isCouponSupported();
            if (!empty($is_coupon_supported)) {
                define('COUPON_TYPE', WECHAT_COUPON);
            } else {
                define('COUPON_TYPE', SYSTEM_COUPON);
            }
            load()->model('activity');

            if (!$this->inMobile) {
                message('支付功能只能在手机上使用');
            }
            $orderid = intval($_GPC['orderid']);
            $order = pdo_fetch("SELECT * FROM " . tablename($this->table_order) . " WHERE id = :id", array(':id' => $orderid));

            $tip = '餐后付款';
            if ($order['dining_mode'] == 2) {
                $tip = '货到付款';
            }

            if ($order['status'] != '0') {
                message('抱歉，您的订单已经付款或是被关闭，请重新进入付款！', referer(), 'error');
            }
            $storeid = intval($order['storeid']);
            $setting = $this->getSetting();
            $store = $this->getStoreById($storeid);
            $is_wechat = 0;
            if ($setting['wechat'] == 1) {
                if ($store['wechat'] == 1) {
                    $is_wechat = 1;
                }
            }
            $is_alipay = 0;
            if ($setting['alipay'] == 1) {
                if ($store['alipay'] == 1) {
                    $is_alipay = 1;
                }
            }
            $is_credit = 0;
            if ($setting['credit'] == 1) {
                if ($store['credit'] == 1) {
                    $is_credit = 1;
                }
            }
            $is_delivery = 0;
            if ($setting['delivery'] == 1) {
                if ($store['delivery'] == 1) {
                    $is_delivery = 1;
                }
            }

            $params['tid'] = $orderid;
            $params['user'] = $_W['fans']['from_user'];
            $params['fee'] = $order['totalprice'];
            $params['ordersn'] = $order['ordersn'];
            $params['virtual'] = true;
            $params['module'] = 'weisrc_dish';
            $params['title'] = '餐饮' . $order['ordersn'];
            $log = pdo_get('core_paylog', array('uniacid' => $_W['uniacid'], 'module' => $params['module'], 'tid' => $params['tid']));
            if (empty($log)) {
                $log = array(
                    'uniacid' => $_W['uniacid'],
                    'acid' => $_W['acid'],
                    'openid' => $_W['member']['uid'],
                    'module' => $this->module['name'], //模块名称，请保证$this可用
                    'tid' => $params['tid'],
                    'fee' => $params['fee'],
                    'card_fee' => $params['fee'],
                    'status' => '0',
                    'is_usecard' => '0',
                );
                pdo_insert('core_paylog', $log);
            }

            if ($log['status'] == '1') {
                message('这个订单已经支付成功, 不需要重复支付.');
            }
            $setting = uni_setting($_W['uniacid'], array('payment', 'creditbehaviors'));
            if (!is_array($setting['payment'])) {
                message('没有有效的支付方式, 请联系网站管理员.');
            }
            $pay = $setting['payment'];

            $cards = activity_paycenter_coupon_available();

            if (!empty($cards)) {

                foreach ($cards as $key => &$val) {

                    if ($val['type'] == '1') {

                        $val['discount_cn'] = sprintf("%.2f", $params['fee'] * (1 - $val['extra']['discount'] * 0.01));

                        $coupon[$key] = $val;

                    } else {

                        $val['discount_cn'] = sprintf("%.2f", $val['extra']['reduce_cost'] * 0.01);

                        $token[$key] = $val;

                        if ($log['fee'] < $val['extra']['least_cost'] * 0.01) {

                            unset($token[$key]);

                        }

                    }

                    unset($val['icon']);

                }

            }

            $cards_str = json_encode($cards);

            if (empty($_W['member']['uid'])) {

                $pay['credit']['switch'] = false;

            }

            if ($params['module'] == 'paycenter') {

                $pay['delivery']['switch'] = false;

                $pay['line']['switch'] = false;

            }

            if (!empty($pay['credit']['switch'])) {

                $credtis = mc_credit_fetch($_W['member']['uid']);

            }

            $you = 0;
        } else {
            if (!$this->inMobile) {
                message('支付功能只能在手机上使用');
            }
            $orderid = intval($_GPC['orderid']);
            $order = pdo_fetch("SELECT * FROM " . tablename($this->table_order) . " WHERE id = :id", array(':id' => $orderid));
            if ($order['status'] != '0') {
                message('抱歉，您的订单已经付款或是被关闭，请重新进入付款！', referer(), 'error');
            }

            $tip = '餐后付款';
            if ($order['dining_mode'] == 2) {
                $tip = '货到付款';
            }

            $storeid = intval($order['storeid']);
            $setting = $this->getSetting();
            $store = $this->getStoreById($storeid);
            $is_wechat = 0;
            if ($setting['wechat'] == 1) {
                if ($store['wechat'] == 1) {
                    $is_wechat = 1;
                }
            }
            $is_alipay = 0;
            if ($setting['alipay'] == 1) {
                if ($store['alipay'] == 1) {
                    $is_alipay = 1;
                }
            }
            $is_credit = 0;
            if ($setting['credit'] == 1) {
                if ($store['credit'] == 1) {
                    $is_credit = 1;
                }
            }
            $is_delivery = 0;
            if ($setting['delivery'] == 1) {
                if ($store['delivery'] == 1) {
                    $is_delivery = 1;
                }
            }

            $params['tid'] = $orderid;
            $params['user'] = $_W['fans']['from_user'];
            $params['fee'] = $order['totalprice'];
            $params['ordersn'] = $order['ordersn'];
            $params['virtual'] = true;
            $params['module'] = 'weisrc_dish';
            $params['title'] = '餐饮' . $order['ordersn'];
            $log = pdo_get('core_paylog', array('uniacid' => $_W['uniacid'], 'module' => $params['module'], 'tid' => $params['tid']));
            if (empty($log)) {
                $log = array(
                    'uniacid' => $_W['uniacid'],
                    'acid' => $_W['acid'],
                    'openid' => $_W['member']['uid'],
                    'module' => $this->module['name'], //模块名称，请保证$this可用
                    'tid' => $params['tid'],
                    'fee' => $params['fee'],
                    'card_fee' => $params['fee'],
                    'status' => '0',
                    'is_usecard' => '0',
                );
                pdo_insert('core_paylog', $log);
            }

            if ($log['status'] == '1') {
                message('这个订单已经支付成功, 不需要重复支付.');
            }
            $setting = uni_setting($_W['uniacid'], array('payment', 'creditbehaviors'));
            if (!is_array($setting['payment'])) {
                message('没有有效的支付方式, 请联系网站管理员.');
            }
            $pay = $setting['payment'];
            if (empty($_W['member']['uid'])) {
                $pay['credit']['switch'] = false;
            }
            if (!empty($pay['credit']['switch'])) {
                $credtis = mc_credit_fetch($_W['member']['uid']);
            }
            $you = 0;
            if ($pay['card']['switch'] == 2 && !empty($_W['openid'])) {
                if ($_W['card_permission'] == 1 && !empty($params['module'])) {
                    $cards = pdo_fetchall('SELECT a.id,a.card_id,a.cid,b.type,b.title,b.extra,b.is_display,b.status,b.date_info FROM ' . tablename('coupon_modules') . ' AS a LEFT JOIN ' . tablename('coupon') . ' AS b ON a.cid = b.id WHERE a.acid = :acid AND a.module = :modu AND b.is_display = 1 AND b.status = 3 ORDER BY a.id DESC', array(':acid' => $_W['acid'], ':modu' => $params['module']));
                    $flag = 0;
                    if (!empty($cards)) {
                        foreach ($cards as $temp) {
                            $temp['date_info'] = iunserializer($temp['date_info']);
                            if ($temp['date_info']['time_type'] == 1) {
                                $starttime = strtotime($temp['date_info']['time_limit_start']);
                                $endtime = strtotime($temp['date_info']['time_limit_end']);
                                if (TIMESTAMP < $starttime || TIMESTAMP > $endtime) {
                                    continue;
                                } else {
                                    $param = array(':acid' => $_W['acid'], ':openid' => $_W['openid'], ':card_id' => $temp['card_id']);
                                    $num = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('coupon_record') . ' WHERE acid = :acid AND openid = :openid AND card_id = :card_id AND status = 1', $param);
                                    if ($num <= 0) {
                                        continue;
                                    } else {
                                        $flag = 1;
                                        $card = $temp;
                                        break;
                                    }
                                }
                            } else {
                                $deadline = intval($temp['date_info']['deadline']);
                                $limit = intval($temp['date_info']['limit']);
                                $param = array(':acid' => $_W['acid'], ':openid' => $_W['openid'], ':card_id' => $temp['card_id']);
                                $record = pdo_fetchall('SELECT addtime,id,code FROM ' . tablename('coupon_record') . ' WHERE acid = :acid AND openid = :openid AND card_id = :card_id AND status = 1', $param);
                                if (!empty($record)) {
                                    foreach ($record as $li) {
                                        $time = strtotime(date('Y-m-d', $li['addtime']));
                                        $starttime = $time + $deadline * 86400;
                                        $endtime = $time + $deadline * 86400 + $limit * 86400;
                                        if (TIMESTAMP < $starttime || TIMESTAMP > $endtime) {
                                            continue;
                                        } else {
                                            $flag = 1;
                                            $card = $temp;
                                            break;
                                        }
                                    }
                                }
                                if ($flag) {
                                    break;
                                }
                            }
                        }
                    }
                    if ($flag) {
                        if ($card['type'] == 'discount') {
                            $you = 1;
                            $card['fee'] = sprintf("%.2f", ($params['fee'] * ($card['extra'] / 100)));
                        } elseif ($card['type'] == 'cash') {
                            $cash = iunserializer($card['extra']);
                            if ($params['fee'] >= $cash['least_cost']) {
                                $you = 1;
                                $card['fee'] = sprintf("%.2f", ($params['fee'] - $cash['reduce_cost']));
                            }
                        }
                        load()->classs('coupon');
                        $acc = new coupon($_W['acid']);
                        $card_id = $card['card_id'];
                        $time = TIMESTAMP;
                        $randstr = random(8);
                        $sign = array($card_id, $time, $randstr, $acc->account['key']);
                        $signature = $acc->SignatureCard($sign);
                        if (is_error($signature)) {
                            $you = 0;
                        }
                    }
                }
            }

            if ($pay['card']['switch'] == 3 && $_W['member']['uid']) {
                $cards = array();
                if (!empty($params['module'])) {
                    $cards = pdo_fetchall('SELECT a.id,a.couponid,b.type,b.title,b.discount,b.condition,b.starttime,b.endtime FROM ' . tablename('activity_coupon_modules') . ' AS a LEFT JOIN ' . tablename('activity_coupon') . ' AS b ON a.couponid = b.couponid WHERE a.uniacid = :uniacid AND a.module = :modu AND b.condition <= :condition AND b.starttime <= :time AND b.endtime >= :time  ORDER BY a.id DESC', array(':uniacid' => $_W['uniacid'], ':modu' => $params['module'], ':time' => TIMESTAMP, ':condition' => $params['fee']), 'couponid');
                    if (!empty($cards)) {
                        foreach ($cards as $key => &$card) {
                            $has = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('activity_coupon_record') . ' WHERE uid = :uid AND uniacid = :aid AND couponid = :cid AND status = 1' . $condition, array(':uid' => $_W['member']['uid'], ':aid' => $_W['uniacid'], ':cid' => $card['couponid']));
                            if ($has > 0) {
                                if ($card['type'] == '1') {
                                    $card['fee'] = sprintf("%.2f", ($params['fee'] * $card['discount']));
                                    $card['discount_cn'] = sprintf("%.2f", $params['fee'] * (1 - $card['discount']));
                                } elseif ($card['type'] == '2') {
                                    $card['fee'] = sprintf("%.2f", ($params['fee'] - $card['discount']));
                                    $card['discount_cn'] = $card['discount'];
                                }
                            } else {
                                unset($cards[$key]);
                            }
                        }
                    }
                }
                if (!empty($cards)) {
                    $cards_str = json_encode($cards);
                }
            }
        }
        //美丽心情
        if ($store['is_business'] == 1) {
            $business_id = intval($store['business_id']);
            if ($business_id > 0) {
                $url = $_W['siteroot'] . 'app/index.php?i=' . $_W['uniacid'] . '&c=entry&tid=' . $params['tid'] . '&title=' . $params['title'] . '&fee=' . $params['fee'] . '&ordersn=' . $params['ordersn'] . '&user=' . $params['user'] . '&rid=' . $business_id . '&ms=weisrc_dish&do=payex&m=bm_payu';
                Header("Location: {$url}");
            }
        }

        if (IMS_VERSION == '0.8') {
            include $this->template('paycenter_v8');
        } else {
            include $this->template('paycenter');
        }
    }

    private function sendText($openid, $content)
    {
        $send['touser'] = trim($openid);
        $send['msgtype'] = 'text';
        $send['text'] = array('content' => urlencode($content));
        $acc = WeAccount::create();
        $data = $acc->sendCustomNotice($send);
        return $data;
    }

    public function payResult($params)
    {
        global $_W, $_GPC;
        $weid = $this->_weid;
        $orderid = $params['tid'];
        $fee = intval($params['fee']);
        $paytype = array('credit' => '1', 'wechat' => '2', 'alipay' => '4', 'baifubao' => '5', 'delivery' => '3');

        // 卡券代金券备注
        if (!empty($params['is_usecard'])) {
            $cardType = array('1' => '微信卡券', '2' => '系统代金券');
            $result_price = ($params['fee'] - $params['card_fee']);
            $data['paydetail'] = '使用' . $cardType[$params['card_type']] . '支付了' . $result_price;
            $data['paydetail'] .= '元，实际支付了' . $params['card_fee'] . '元。';
            $data['totalprice'] = $params['card_fee'];
        }

        $data['paytype'] = $paytype[$params['type']];

        if ($params['type'] == 'alipay') {
            if (!empty($params['transaction_id'])) {
                $data['transid'] = $params['transaction_id'];
            }
        }
        if ($params['type'] == 'wechat') {
            if (!empty($params['tag']['transaction_id'])) {
                $data['transid'] = $params['tag']['transaction_id'];
            }
        }

        if ($params['type'] == 'delivery') {
//            $data['status'] = 1;
        }

        $order = pdo_fetch("SELECT * FROM " . tablename($this->table_order) . " WHERE id = :id", array(':id' => $orderid));
        if (empty($order)) {
            message('订单不存在!');
        }

        if (!empty($order) && $order['status'] == 0) {
            if ($data['paytype'] == 1 || $data['paytype'] == 2 || $data['paytype'] == 4) { //在线，余额支付
                $data['ispay'] = 1;
            }

            pdo_update($this->table_order, $data, array('id' => $orderid));
            $storeid = $order['storeid'];
            $store = pdo_fetch("SELECT * FROM " . tablename($this->table_stores) . " WHERE id=:id LIMIT 1", array(':id' => $storeid));

            //本订单产品
            $goods = pdo_fetchall("SELECT a.*,b.title,b.unitname FROM " . tablename($this->table_order_goods) . " as a left join  " . tablename($this->table_goods) . " as b on a.goodsid=b.id WHERE a.orderid=:orderid ", array(':orderid' => $orderid));
            $goods_str = '';
            $goods_tplstr = '';
            $flag = false;
            foreach ($goods as $key => $value) {
                if (!$flag) {
                    $goods_str .= "{$value['title']} 价格：{$value['price']} 数量：{$value['total']}{$value['unitname']}";
                    $goods_tplstr .= "{$value['title']} {$value['total']}{$value['unitname']}";
                    $flag = true;
                } else {
                    $goods_str .= "<br/>{$value['title']} 价格：{$value['price']} 数量：{$value['total']}{$value['unitname']}";
                    $goods_tplstr .= ",{$value['title']} {$value['total']}{$value['unitname']}";
                }
            }

            if ($order['dining_mode'] == 1) {
                if ($data['paytype'] == 3) { //现金
                    pdo_update($this->table_tables, array('status' => 2), array('id' => $order['tables']));
                } else {
                    pdo_update($this->table_tables, array('status' => 3), array('id' => $order['tables']));
                }
            }
            if ($data['paytype'] == 1 || $data['paytype'] == 2 || $data['paytype'] == 4) { //在线，余额支付
                pdo_update($this->table_order, array('ispay' => 1), array('id' => $orderid));
            }

            $setting = pdo_fetch("select * from " . tablename($this->table_setting) . " where weid =:weid LIMIT 1", array(':weid' => $order['weid']));

            //后台通知，修改状态
            if ($params['result'] == 'success' && $params['from'] == 'notify') {
                file_put_contents(IA_ROOT . "/addons/weisrc_dish/params.log", var_export($params, true) . PHP_EOL, FILE_APPEND);
                if ($params['type'] == 'alipay') {
                    if (empty($params['transaction_id'])) {
                        return false;
                    }
                }
                if ($params['type'] == 'wechat') {
                    if (empty($params['tag']['transaction_id'])) {
                        return false;
                    }
                }

                if ($order['istpl'] == 0) {
                    if ($params['type'] == 'credit') {
                        pdo_update($this->table_order, array('istpl' => 1), array('id' => $orderid));
                    }

                    $this->feiyinSendFreeMessage($orderid);
                    $this->_365SendFreeMessage($orderid);
                    $this->feieSendFreeMessage($orderid);
                    $this->_yilianyunSendFreeMessage($orderid);
                    $order = pdo_fetch("SELECT * FROM " . tablename($this->table_order) . " WHERE id = :id", array(':id' => $orderid));
                    //用户
                    $this->sendOrderNotice($order, $store, $setting);
                    //管理
                    if (!empty($setting)) {
                        //平台提醒
                        if ($setting['is_notice'] == 1) {
                            if (!empty($setting['tpluser'])) {
                                $tousers = explode(',', $setting['tpluser']);
                                foreach ($tousers as $key => $value) {
                                    $this->sendAdminOrderNotice($orderid, $value, $setting);
                                }
                            }
                            if (!empty($setting['email'])) {
                                $this->sendAdminOrderEmail($setting['email'], $order, $store, $goods_str);
                            }
                            if (!empty($setting['sms_mobile'])) {
                                $smsStatus = $this->sendAdminOrderSms($setting['sms_mobile'], $order);
                            }
                        }
                        //门店提醒
                        $accounts = pdo_fetchall("SELECT * FROM " . tablename($this->table_account) . " WHERE weid = :weid AND storeid=:storeid AND status=2 ORDER BY id DESC ", array(':weid' => $this->_weid, ':storeid' => $storeid));
                        foreach ($accounts as $key => $value) {
                            if (!empty($value['from_user'])) {
                                $this->sendAdminOrderNotice($orderid, $value['from_user'], $setting);
                            }
                            if (!empty($value['email'])) {
                                $this->sendAdminOrderEmail($value['email'], $order, $store, $goods_str);
                            }
                            if (!empty($value['mobile'])) {
                                $smsStatus = $this->sendAdminOrderSms($value['mobile'], $order);
                            }
                        }
                    }
                    pdo_update($this->table_order, array('istpl' => 1), array('id' => $orderid));
                }
            }

            //前台通知
            if ($params['from'] == 'return') {
                if ($order['istpl'] == 0 && $params['type'] == 'delivery') {
                    $this->feiyinSendFreeMessage($orderid);
                    $this->_365SendFreeMessage($orderid);
                    $this->feieSendFreeMessage($orderid);
                    $this->_yilianyunSendFreeMessage($orderid);
                    $order = pdo_fetch("SELECT * FROM " . tablename($this->table_order) . " WHERE id = :id", array(':id' => $orderid));
                    //用户
                    $this->sendOrderNotice($order, $store, $setting);
                    //管理
                    if (!empty($setting)) {
                        //平台提醒
                        if ($setting['is_notice'] == 1) {
                            if (!empty($setting['tpluser'])) {
                                $tousers = explode(',', $setting['tpluser']);
                                foreach ($tousers as $key => $value) {
                                    $this->sendAdminOrderNotice($orderid, $value, $setting);
                                }
                            }
                            if (!empty($setting['email'])) {
                                $this->sendAdminOrderEmail($setting['email'], $order, $store, $goods_str);
                            }
                            if (!empty($setting['sms_mobile'])) {
                                $smsStatus = $this->sendAdminOrderSms($setting['sms_mobile'], $order);
                            }
                        }
                        //门店提醒
                        $accounts = pdo_fetchall("SELECT * FROM " . tablename($this->table_account) . " WHERE weid = :weid AND storeid=:storeid AND status=2 ORDER BY id DESC ", array(':weid' => $this->_weid, ':storeid' => $storeid));
                        foreach ($accounts as $key => $value) {
                            if (!empty($value['from_user'])) {
                                $this->sendAdminOrderNotice($orderid, $value['from_user'], $setting);
                            }
                            if (!empty($value['email'])) {
                                $this->sendAdminOrderEmail($value['email'], $order, $store, $goods_str);
                            }
                            if (!empty($value['mobile'])) {
                                $smsStatus = $this->sendAdminOrderSms($value['mobile'], $order);
                            }
                        }
                    }
                    pdo_update($this->table_order, array('istpl' => 1), array('id' => $orderid));
                }
            }
        }

        $tip_msg = '支付成功';
        if ($params['type'] == 'delivery') {
            $tip_msg = '下单成功';
        }

        $setting = uni_setting($_W['uniacid'], array('creditbehaviors'));
        $credit = $setting['creditbehaviors']['currency'];
        if ($params['type'] == $credit) {
            if ($params['type'] == 'baifubao') {
                message($tip_msg, '../../app/' . $this->createMobileUrl('orderdetail', array('orderid' => $orderid), true), 'success');
            } else {
                message($tip_msg, $this->createMobileUrl('orderdetail', array('orderid' => $orderid), true), 'success');
            }
        } else {
            $url = '../../app/' . $this->createMobileUrl('orderdetail', array('orderid' => $orderid));
            if ($params['paysys'] == 'payu') {
                Header("Location: {$url}");
            } else {
                message($tip_msg, $url, 'success');
            }
        }
    }

    public function sendOrderEmail($order, $store, $goods_str)
    {
        $firstArr = array(
            '-1' => '已经取消',
            '0' => '已经提交',
            '1' => '已经确认',
            '2' => '已并台',
            '3' => '已经完成'
        );

        $orderStatus = array(
            '-1' => '已取消',
            '0' => '待处理',
            '1' => '已确认',
            '2' => '已并台',
            '3' => '已完成'
        );
        $paytype = array(
            '0' => '现金付款',
            '1' => '余额支付',
            '2' => '微信支付',
            '3' => '现金付款',
            '4' => '支付宝'
        );

        //发送邮件提醒
        $emailSetting = pdo_fetch("SELECT * FROM " . tablename($this->table_setting) . " WHERE weid=:weid AND storeid=:storeid LIMIT 1", array(':weid' => $order['weid'], ':storeid' => $order['storeid']));

        $keyword1 = $order['ordersn'];
        $keyword2 = $orderStatus[$order['status']];
        $keyword3 = date("Y-m-d H:i", $order['dateline']);

        $email_tpl = "
        您的订单{$order['ordersn']}{$firstArr[$order['status']]}<br/>
        订单号：{$keyword1}<br/>
        订单状态：{$keyword2}<br/>
        时间：{$keyword3}<br/>
        门店名称：{$store['title']}<br/>
        支付方式：{$paytype[$order['paytype']]}<br/>
        ";
        if ($order['dining_mode'] == 3) {
            $email_tpl .= "预定人信息：{$order['username']}－{$order['tel']}<br/>";
            $email_tpl .= "预定时间：{$order['meal_time']}<br/>";
        } else {
            $email_tpl .= "联系方式：{$order['username']}－{$order['tel']}<br/>";
        }
        if ($order['dining_mode'] == 1) {
            $tablename = $this->getTableName($order['tables']);
            $email_tpl .= "桌台信息：{$tablename}<br/>";
        }
        if ($order['dining_mode'] == 2) {
            if (!empty($order['address'])) {
                $email_tpl .= "配送地址：{$order['address']}<br/>";
            }
            if (!empty($order['meal_time'])) {
                $email_tpl .= "配送时间：{$order['meal_time']}<br/>";
            }
        }
        $email_tpl .= "菜单：{$goods_str}<br/>";
        $email_tpl .= "备注：{$order['remark']}<br/>";
        $email_tpl .= "应收合计：{$order['totalprice']}";

        if (!empty($emailSetting) && !empty($emailSetting['email'])) {
            if ($emailSetting['email_host'] == 'smtp.qq.com' || $emailSetting['email_host'] == 'smtp.gmail.com') {
                $secure = 'ssl';
                $port = '465';
            } else {
                $secure = 'tls';
                $port = '25';
            }

            $mail_config = array();
            $mail_config['host'] = $emailSetting['email_host'];
            $mail_config['secure'] = $secure;
            $mail_config['port'] = $port;
            $mail_config['username'] = $emailSetting['email_user'];
            $mail_config['sendmail'] = $emailSetting['email_send'];
            $mail_config['password'] = $emailSetting['email_pwd'];
            $mail_config['mailaddress'] = $emailSetting['email'];
            $mail_config['subject'] = '订单提醒';
            $mail_config['body'] = $email_tpl;
            $result = $this->sendmail($mail_config);
        }
    }

    public function checkModule($name)
    {
        $module = pdo_fetch("SELECT * FROM " . tablename("modules") . " WHERE name=:name ", array(':name' => $name));
        return $module;
    }

    //提示信息
    public function showMessageAjax($msg, $code = 0)
    {
        $result['code'] = $code;
        $result['msg'] = $msg;
        message($result, '', 'ajax');
    }

    public function showMsg($msg, $status = 0)
    {
        $result = array('msg' => $msg, 'status' => $status);
        echo json_encode($result);
        exit();
    }

    public function  doMobileAjaxdelete()
    {
        global $_GPC;
        $delurl = $_GPC['pic'];
        load()->func('file');
        if (file_delete($delurl)) {
            echo 1;
        } else {
            echo 0;
        }
    }

    function img_url($img = '')
    {
        global $_W;
        if (empty($img)) {
            return "";
        }
        if (substr($img, 0, 6) == 'avatar') {
            return $_W['siteroot'] . "resource/image/avatar/" . $img;
        }
        if (substr($img, 0, 8) == './themes') {
            return $_W['siteroot'] . $img;
        }
        if (substr($img, 0, 1) == '.') {
            return $_W['siteroot'] . substr($img, 2);
        }
        if (substr($img, 0, 5) == 'http:') {
            return $img;
        }
        return $_W['attachurl'] . $img;
    }

    //发送短信
    public function _sendSms($sendinfo)
    {
        global $_W;
        load()->func('communication');
        $weid = $_W['uniacid'];
        $username = $sendinfo['username'];
        $pwd = $sendinfo['pwd'];
        $mobile = $sendinfo['mobile'];
        $content = $sendinfo['content'];
        $target = "http://www.dxton.com/webservice/sms.asmx/Submit";
        //替换成自己的测试账号,参数顺序和wenservice对应
        $post_data = "account=" . $username . "&password=" . $pwd . "&mobile=" . $mobile . "&content=" . rawurlencode($content);
        //请自己解析$gets字符串并实现自己的逻辑
        //<result>100</result>表示成功,其它的参考文档

        $result = ihttp_request($target, $post_data);
        $xml = simplexml_load_string($result['content'], 'SimpleXMLElement', LIBXML_NOCDATA);
        $result = (string)$xml->result;
        $message = (string)$xml->message;
        return $result;
    }

    public function sendmail($config)
    {
        require_once 'plugin/email/class.phpmailer.php';
        $mail = new PHPMailer();
        $mail->CharSet = "utf-8";
        $body = $config['body'];
        $mail->IsSMTP();
        $mail->SMTPAuth = true; // enable SMTP authentication
        $mail->SMTPSecure = $config['secure']; // sets the prefix to the servier
        $mail->Host = $config['host']; // sets the SMTP server
        $mail->Port = $config['port'];
        $mail->Username = $config['sendmail']; // 发件邮箱用户名
        $mail->Password = $config['password']; // 发件邮箱密码
        $mail->From = $config['sendmail']; //发件邮箱
        $mail->FromName = $config['username']; //发件人名称
        $mail->Subject = $config['subject']; //主题
        $mail->WordWrap = 50; // set word wrap
        $mail->MsgHTML($body);
        $mail->AddAddress($config['mailaddress'], ''); //收件人地址、名称
        $mail->IsHTML(true); // send as HTML
        if (!$mail->Send()) {
            $status = 0;
        } else {
            $status = 1;
        }
        return $status;
    }

    public function doMobileValidatecheckcode()
    {
        global $_W, $_GPC;
        $weid = $this->_weid;
        $from_user = $_GPC['from_user'];
        $this->_fromuser = $from_user;
        $mobile = trim($_GPC['mobile']);
        $checkcode = trim($_GPC['checkcode']);

        if (empty($mobile)) {
            $this->showMsg('请输入手机号码!');
        }

        if (empty($checkcode)) {
            $this->showMsg('请输入验证码!');
        }

        $item = pdo_fetch("SELECT * FROM " . tablename('weisrc_dish_sms_checkcode') . " WHERE weid = :weid  AND from_user=:from_user AND checkcode=:checkcode ORDER BY `id` DESC limit 1", array(':weid' => $weid, ':from_user' => $from_user, ':checkcode' => $checkcode));

        if (empty($item)) {
            $this->showMsg('验证码输入错误!');
        } else {
            pdo_update('weisrc_dish_sms_checkcode', array('status' => 1), array('id' => $item['id']));
            pdo_update($this->table_fans, array('mobile' => $item['mobile']), array('from_user' => $item['from_user'], 'weid' => $weid));
        }

        $this->showMsg('验证成功!', 1);
    }

    //取得短信验证码
    public function doMobileGetCheckCode()
    {
        global $_W, $_GPC;
        $weid = $this->_weid;
        $from_user = trim($_GPC['from_user']);
        $this->_fromuser = $from_user;
        $mobile = trim($_GPC['mobile']);
        $storeid = intval($_GPC['storeid']);

        if (!preg_match("/^13[0-9]{1}[0-9]{8}$|15[0-9]{1}[0-9]{8}$|17[0-9]{1}[0-9]{8}$|18[0-9]{1}[0-9]{8}$|147[0-9]{8
        }$/", $mobile)
        ) {
            $this->showMsg('手机号码格式不对!');
        }

        $passcheckcode = pdo_fetch("SELECT * FROM " . tablename('weisrc_dish_sms_checkcode') . " WHERE weid = :weid  AND from_user=:from_user AND status=1 ORDER BY `id` DESC limit 1", array(':weid' => $weid, ':from_user' => $from_user));
        if (!empty($passcheckcode)) {
            $this->showMsg('发送成功!', 1);
        }

        $smsSetting = pdo_fetch("SELECT * FROM " . tablename($this->table_setting) . " WHERE weid=:weid LIMIT 1", array(':weid' => $weid));
        if (empty($smsSetting) || empty($smsSetting['sms_username']) || empty($smsSetting['sms_pwd'])) {
            $this->showMsg('商家未开启验证码!');
        }

        $checkCodeCount = pdo_fetchcolumn("SELECT count(1) FROM " . tablename('weisrc_dish_sms_checkcode') . " WHERE weid = :weid  AND from_user=:from_user ", array(':weid' => $weid, ':from_user' => $from_user));
        if ($checkCodeCount >= 3) {
            $this->showMsg('您请求的验证码已超过最大限制..' . $checkCodeCount);
        }

        //判断数据是否已经存在
        $data = pdo_fetch("SELECT * FROM " . tablename('weisrc_dish_sms_checkcode') . " WHERE weid = :weid  AND from_user=:from_user ORDER BY `id` DESC limit 1", array(':weid' => $weid, ':from_user' => $from_user));
        if (!empty($data)) {
            if (TIMESTAMP - $data['dateline'] < 60) {
                $this->showMsg('每分钟只能获取短信一次!');
            }
        }

        //验证码
        $checkcode = random(6, 1);
        $checkcode = $this->getNewCheckCode($checkcode);
        $data = array(
            'weid' => $weid,
            'from_user' => $from_user,
            'mobile' => $mobile,
            'checkcode' => $checkcode,
            'status' => 0,
            'dateline' => TIMESTAMP
        );

        $sendInfo = array();
        $sendInfo['username'] = $smsSetting['sms_username'];
        $sendInfo['pwd'] = $smsSetting['sms_pwd'];
        $sendInfo['mobile'] = $mobile;
        $sendInfo['content'] = "您的验证码是：" . $checkcode . "。如需帮助请联系客服。";
        $return_result_code = $this->_sendSms($sendInfo);
        if ($return_result_code != '100') {
            $code_msg = $this->sms_status[$return_result_code];
            $this->showMsg($code_msg . $return_result_code);
        } else {
            pdo_insert('weisrc_dish_sms_checkcode', $data);
            $this->showMsg('发送成功!', 1);
        }
    }

    public function getNewCheckCode($checkcode)
    {
        global $_W, $_GPC;
        $weid = $this->_weid;
        $from_user = $this->_from_user;

        $data = pdo_fetch("SELECT checkcode FROM " . tablename('weisrc_dish_sms_checkcode') . " WHERE weid = :weid AND checkcode = :checkcode AND from_user=:from_user ORDER BY `id` DESC limit 1", array(':weid' => $weid, ':checkcode' => $checkcode, ':from_user' => $from_user));

        if (!empty($data)) {
            $checkcode = random(6, 1);
            $this->getNewCheckCode($checkcode);
        }
        return $checkcode;
    }

    //打印数据
    public function doWebPrint()
    {
        global $_W, $_GPC;
        $weid = $_W['uniacid'];
        $usr = !empty($_GET['usr']) ? $_GET['usr'] : '355839026790719';
        $ord = !empty($_GET['ord']) ? $_GET['ord'] : 'no';
        $sgn = !empty($_GET['sgn']) ? $_GET['sgn'] : 'no';

        header('Content-type: text/html; charset=gbk');

        $print_type_confirmed = 0;
        $print_type_payment = 1;

        //更新打印状态
        if (isset($_GET['sta'])) {
            $id = intval($_GPC['id']); //订单id
            $sta = intval($_GPC['sta']); //状态

            pdo_update($this->table_print_order, array('print_status' => $sta), array('orderid' => $id, 'print_usr' => $usr));
            //id —— 平台下发打印数据的id号,打印机打印后回复打印是否成功带此id号。
            //usr -- 打印机终端系统的IMEI号码或SIM卡的IMSI号码
            //sta —— 打印机状态(0为打印成功, 1为过热,3为缺纸卡纸等)
            exit;
        }

        //打印机配置信息
        $setting = pdo_fetch("SELECT * FROM " . tablename($this->table_print_setting) . " WHERE print_usr = :usr AND print_status=1 AND type='hongxin'", array(':usr' => $usr));
        if ($setting == false) {
            exit;
        }

        //门店id
        $storeid = $setting['storeid'];

        $condition = "";
        if ($setting['print_type'] == $print_type_confirmed) {
            //已确认订单 //status == 1
            $condition = ' AND paytype>0 ';
        } else if ($setting['print_type'] == $print_type_payment) {
            //已付款订单 //已完成
            $condition = ' AND (ispay=1 or status=3) ';
        }

        //根据订单id读取相关订单
        $order = pdo_fetch("SELECT * FROM " . tablename($this->table_order) . " WHERE  id IN(SELECT orderid FROM "
            . tablename('weisrc_dish_print_order') . " WHERE print_status=-1 AND
print_usr=:print_usr) AND storeid = :storeid {$condition} ORDER BY id DESC limit 1", array(':storeid' => $storeid, ':print_usr' => $usr));

        //没有新订单
        if ($order == false) {
            message('no data!');
            exit;
        }

        //商品id数组
        $goodsid = pdo_fetchall("SELECT goodsid, total FROM " . tablename($this->table_order_goods) . " WHERE orderid = '{$order['id']}'", array(), 'goodsid');

        //商品
        $goods = pdo_fetchall("SELECT * FROM " . tablename($this->table_goods) . "  WHERE id IN ('" . implode("','", array_keys($goodsid)) . "')");
        $order['goods'] = $goods;

        if (!empty($setting['print_top'])) {
            $content = "%10" . $setting['print_top'] . "\n";
        } else {
            $content = '';
        }
        $ordertype = array(
            '1' => '堂点',
            '2' => '外卖',
            '3' => '预定',
            '4' => '快餐'
        );
        $store = pdo_fetch("SELECT * FROM " . tablename($this->table_stores) . " WHERE  id =:id ORDER BY id DESC limit 1", array(':id' => $order['storeid']));
        $paytype = array('0' => '线下付款', '1' => '余额支付', '2' => '微信支付', '3' => $order['dining_mode']==1?'餐后付款':'货到付款',
            '4' => '支付宝');
        $content .= '%00单号:' . $order['ordersn'] . "\n";
        $content .= '订单类型:' . $ordertype[$order['dining_mode']] . "\n";
        $content .= '所属门店:' . $store['title'] . "\n";
        $content .= '支付方式:' . $paytype[$order['paytype']] . "\n";
        $content .= '下单日期:' . date('Y-m-d H:i:s', $order['dateline']) . "\n";
        $content .= '预约时间:' . $order['meal_time'] . "\n";
        if ($order['dining_mode'] == 3) {
            $tablezones = pdo_fetch("SELECT * FROM " . tablename($this->table_tablezones) . " where id=:id LIMIT 1", array(':id' => $order['tablezonesid']));
            $content .= "桌台类型：{$tablezones['title']}\n";
        }
        if (!empty($order['tables'])) {
            $content .= '桌台信息:' . $this->getTableName($order['tables']) . "\n";
        }

        if (!empty($order['remark'])) {
            $content .= '%10备注:' . $order['remark'] . "\n";
        }
        if (!empty($goods)) {
            $content .= "%00\n名称              数量  单价 \n";
            $content .= "----------------------------\n%10";
        }

        $content1 = '';
        foreach ($order['goods'] as $v) {
            $money = $v['marketprice'];
            $content1 .= $this->stringformat($v['title'], 16) . $this->stringformat($goodsid[$v['id']]['total'], 4, false) . $this->stringformat(number_format($money, 2), 7, false) . "\n\n";
        }

        $content2 = "----------------------------\n";
        $content2 .= "%10总数量:" . $order['totalnum'] . "   总价:" . number_format($order['totalprice'], 2) . "元\n%00";
        if (!empty($order['username'])) {
            $content2 .= '姓名:' . $order['username'] . "\n";
        }
        if (!empty($order['tel'])) {
            $content2 .= '手机:' . $order['tel'] . "\n";
        }
        if (!empty($order['address'])) {
            $content2 .= '地址:' . $order['address'] . "\n";
        }

        if (!empty($setting['qrcode_status'])) {
            $qrcode_url = trim($setting['qrcode_url']);
            if (!empty($qrcode_url)) {
                $content2 .= "%%%50372C" . $qrcode_url . "\n";
            }
        }

        //$content2 .= "%%%50372Chttp://www.weisrc.com\n";

        if (!empty($setting['print_bottom'])) {
            $content2 .= "%10" . $setting['print_bottom'] . "\n%00";
        }

        $content = iconv("UTF-8", "GB2312//IGNORE", $content);
        $content1 = iconv("UTF-8", "GB2312//IGNORE", $content1);
        $content2 = iconv("UTF-8", "GB2312//IGNORE", $content2);

        $setting = '<setting>124:' . $setting['print_nums'] . '|134:0</setting>';
        $setting = iconv("UTF-8", "GB2312//IGNORE", $setting);
        echo '<?xml version="1.0" encoding="GBK"?><r><id>' . $order['id'] . '</id><time>' . date('Y-m-d H:i:s', $order['dateline']) . '</time><content>' . $content . $content1 . $content2 . '</content>' . $setting . '</r>';
    }

    //用户打印机处理订单
    private function stringformat($string, $length = 0, $isleft = true)
    {
        $substr = '';
        if ($length == 0 || $string == '') {
            return $string;
        }
        if (strlen($string) > $length) {
            for ($i = 0; $i < $length; $i++) {
                $substr = $substr . "_";
            }
            $string = $string . '%%' . $substr;
        } else {
            for ($i = strlen($string); $i < $length; $i++) {
                $substr = $substr . " ";
            }
            $string = $isleft ? ($string . $substr) : ($substr . $string);
        }
        return $string;
    }

    public function oauth2($url)
    {
        global $_GPC, $_W;
        load()->func('communication');
        $code = $_GPC['code'];
        if (empty($code)) {
            message('code获取失败.');
        }
        $token = $this->getAuthorizationCode($code);
        $from_user = $token['openid'];
        $userinfo = $this->getUserInfo($from_user);
        $sub = 1;
        if ($userinfo['subscribe'] == 0) {
            //未关注用户通过网页授权access_token
            $sub = 0;
            $authkey = intval($_GPC['authkey']);
            if ($authkey == 0) {
                $oauth2_code = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $this->_appid . "&redirect_uri=" . urlencode($url) . "&response_type=code&scope=snsapi_userinfo&state=0#wechat_redirect";
                header("location:$oauth2_code");
            }
            $userinfo = $this->getUserInfo($from_user, $token['access_token']);
        }

        if (empty($userinfo) || !is_array($userinfo) || empty($userinfo['openid']) || empty($userinfo['nickname'])) {
            echo '<h1>获取微信公众号授权失败[无法取得userinfo], 请稍后重试！ 公众平台返回原始数据为: <br />' . $sub . $userinfo['meta'] . '<h1>';
            exit;
        }

        //设置cookie信息
        setcookie($this->_auth2_headimgurl, $userinfo['headimgurl'], time() + 3600 * 24);
        setcookie($this->_auth2_nickname, $userinfo['nickname'], time() + 3600 * 24);
        setcookie($this->_auth2_openid, $from_user, time() + 3600 * 24);
        setcookie($this->_auth2_sex, $userinfo['sex'], time() + 3600 * 24);
//        print_r($userinfo);
//        exit;
        return $userinfo;
    }

    public function getUserInfo($from_user, $ACCESS_TOKEN = '')
    {
        if ($ACCESS_TOKEN == '') {
            $ACCESS_TOKEN = $this->getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$ACCESS_TOKEN}&openid={$from_user}&lang=zh_CN";
        } else {
            $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$ACCESS_TOKEN}&openid={$from_user}&lang=zh_CN";
        }

        $json = ihttp_get($url);
        $userInfo = @json_decode($json['content'], true);
        return $userInfo;
    }

    public function getAuthorizationCode($code)
    {
        $oauth2_code = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->_appid}&secret={$this->_appsecret}&code={$code}&grant_type=authorization_code";
        $content = ihttp_get($oauth2_code);
        $token = @json_decode($content['content'], true);
        if (empty($token) || !is_array($token) || empty($token['access_token']) || empty($token['openid'])) {
            $oauth2_code = $this->createMobileUrl('waprestlist', array(), true);
            header("location:$oauth2_code");
//            echo '微信授权失败, 请稍后重试! 公众平台返回原始数据为: <br />' . $content['meta'] . '<h1>';
            exit;
        }
        return $token;
    }

    public function getAccessToken()
    {
        global $_W;
        $account = $_W['account'];
        if ($this->_accountlevel < 4) {
            if (!empty($this->_account)) {
                $account = $this->_account;
            }
        }
        load()->classs('weixin.account');
        $accObj = WeixinAccount::create($account['acid']);
        $access_token = $accObj->fetch_token();
        return $access_token;
    }

    public function getCode($url)
    {
        global $_W;
        $url = urlencode($url);
        $oauth2_code = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->_appid}&redirect_uri={$url}&response_type=code&scope=snsapi_base&state=0#wechat_redirect";
        header("location:$oauth2_code");
    }

    public $actions_titles = array(
        'stores' => '门店信息',
//        'statistics' => '统计中心',
        'order' => '订单管理',
        'coupon' => '促销管理',
        'tables' => '餐桌管理',
        'queueorder' => '排号管理',
        'fans' => '会员管理',
        'goods' => '商品管理',
        'category' => '商品类别',
        'intelligent' => '智能推荐',
        'reservation' => '预定管理',
        'feedback' => '评论管理',
        'printsetting' => '打印机设置',
        'businesscenter' => '商户中心',
        'savewine' => '寄存管理',
    );

    public $sms_status = array(
        '100' => '发送成功',
        '101' => '验证失败',
        '102' => '手机号码格式不正确',
        '103' => '会员级别不够',
        '104' => '内容未审核',
        '105' => '内容过多',
        '106' => '账户余额不足',
        '107' => 'Ip受限',
        '108' => '手机号码发送太频繁，请换号或隔天再发',
        '109' => '帐号被锁定',
        '110' => '手机号发送频率持续过高，黑名单屏蔽数日',
        '111' => '系统升级',
    );

    public function doWebDeletemealtime()
    {
        global $_W, $_GPC;
        $weid = $this->_weid;
        $id = intval($_GPC['id']);
        $storeid = intval($_GPC['storeid']);

        if (empty($storeid)) {
            $url = $this->createWebUrl('stores', array('op' => 'post', 'id' => $storeid));
        }

        pdo_delete('weisrc_dish_mealtime', array('id' => $id, 'weid' => $weid));
        message('操作成功', $url, 'success');
    }

    public function doWebSetAdProperty()
    {
        global $_GPC, $_W;
        $id = intval($_GPC['id']);
        $type = $_GPC['type'];
        $data = intval($_GPC['data']);
        empty($data) ? ($data = 1) : $data = 0;
        if (!in_array($type, array('status'))) {
            die(json_encode(array("result" => 0)));
        }
        pdo_update($this->table_ad, array($type => $data), array("id" => $id, "uniacid" => $_W['uniacid']));
        die(json_encode(array("result" => 1, "data" => $data)));
    }

    //统计中心
    public function doWebStatistics()
    {
        global $_W, $_GPC, $code;
        $weid = $this->_weid;
        $returnid = $this->checkPermission();
        $action = 'statistics';
        $title = '统计中心';
        $storeid = intval($_GPC['storeid']);
        if (empty($storeid)) {
            message('请选择门店!');
        }
        $url = $this->createWebUrl($action, array('op' => 'display'));
        $operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
        if ($operation == 'display') {
            $shoptypeid = intval($_GPC['shoptypeid']);
            $areaid = intval($_GPC['areaid']);
            $keyword = trim($_GPC['keyword']);

            if (checksubmit('submit')) { //排序
                if (is_array($_GPC['displayorder'])) {
                    foreach ($_GPC['displayorder'] as $id => $val) {
                        $data = array('displayorder' => intval($_GPC['displayorder'][$id]));
                        pdo_update($this->table_stores, $data, array('id' => $id));
                    }
                }
                message('操作成功!', $url);
            }
            $pindex = max(1, intval($_GPC['page']));
            $psize = 10;
            $where = "WHERE weid = {$weid}";

            if (!empty($keyword)) {
                $where .= " AND title LIKE '%{$keyword}%'";
            }
            if ($shoptypeid != 0) {
                $where .= " AND typeid={$shoptypeid} ";
            }
            if ($areaid != 0) {
                $where .= " AND areaid={$areaid} ";
            }
            if ($returnid != 0) {
                $where .= " AND id={$returnid} ";
            }

            $storeslist = pdo_fetchall("SELECT * FROM " . tablename($this->table_stores) . " {$where} order by displayorder desc,id desc LIMIT " . ($pindex - 1) * $psize . ",{$psize}");
            if (!empty($storeslist)) {
                $total = pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename($this->table_stores) . " $where");
                $pager = pagination($total, $pindex, $psize);
            }
        } elseif ($operation == 'post') {
            load()->func('tpl');
            $id = intval($_GPC['id']); //门店编号
            $reply = pdo_fetch("select * from " . tablename($this->table_stores) . " where id=:id and weid =:weid", array(':id' => $id, ':weid' => $weid));
            $timelist = pdo_fetchall("SELECT * FROM " . tablename('weisrc_dish_mealtime') . " WHERE weid = :weid AND storeid=:storeid order by id", array(':weid' => $weid, ':storeid' => $id));

            if (empty($reply)) {
                $reply['begintime'] = "09:00";
                $reply['endtime'] = "18:00";
            }

            $piclist = unserialize($reply['thumb_url']);

            if (checksubmit('submit')) {
                $data = array(
                    'weid' => intval($_W['uniacid']),
                    'areaid' => intval($_GPC['area']),
                    'typeid' => intval($_GPC['type']),
                    'title' => trim($_GPC['title']),
                    'info' => trim($_GPC['info']),
                    'from_user' => trim($_GPC['from_user']),
                    'content' => trim($_GPC['content']),
                    'tel' => trim($_GPC['tel']),
                    'announce' => trim($_GPC['announce']),
                    'logo' => trim($_GPC['logo']),
                    'address' => trim($_GPC['address']),
                    'location_p' => trim($_GPC['location_p']),
                    'location_c' => trim($_GPC['location_c']),
                    'location_a' => trim($_GPC['location_a']),
                    'lng' => trim($_GPC['baidumap']['lng']),
                    'lat' => trim($_GPC['baidumap']['lat']),
                    'password' => trim($_GPC['password']),
                    'recharging_password' => trim($_GPC['recharging_password']),
                    'is_show' => intval($_GPC['is_show']),
                    'place' => trim($_GPC['place']),
                    'qq' => trim($_GPC['qq']),
                    'weixin' => trim($_GPC['weixin']),
                    'hours' => trim($_GPC['hours']),
                    'consume' => trim($_GPC['consume']),
                    'level' => intval($_GPC['level']),
                    'enable_wifi' => intval($_GPC['enable_wifi']),
                    'enable_card' => intval($_GPC['enable_card']),
                    'enable_room' => intval($_GPC['enable_room']),
                    'enable_park' => intval($_GPC['enable_park']),
                    'is_meal' => intval($_GPC['is_meal']),
                    'is_delivery' => intval($_GPC['is_delivery']),
                    'is_snack' => intval($_GPC['is_snack']),
                    'is_queue' => intval($_GPC['is_queue']),
                    'is_intelligent' => intval($_GPC['is_intelligent']),
                    'is_reservation' => intval($_GPC['is_reservation']),
                    'is_sms' => intval($_GPC['is_sms']),
                    'is_hot' => intval($_GPC['is_hot']),
                    'btn_reservation' => trim($_GPC['btn_reservation']),
                    'btn_eat' => trim($_GPC['btn_eat']),
                    'btn_delivery' => trim($_GPC['btn_delivery']),
                    'btn_snack' => trim($_GPC['btn_snack']),
                    'btn_queue' => trim($_GPC['btn_queue']),
                    'btn_intelligent' => trim($_GPC['btn_intelligent']),
                    'coupon_title1' => trim($_GPC['coupon_title1']),
                    'coupon_title2' => trim($_GPC['coupon_title2']),
                    'coupon_title3' => trim($_GPC['coupon_title3']),
                    'coupon_link1' => trim($_GPC['coupon_link1']),
                    'coupon_link2' => trim($_GPC['coupon_link2']),
                    'coupon_link3' => trim($_GPC['coupon_link3']),
                    'sendingprice' => trim($_GPC['sendingprice']),
                    'dispatchprice' => trim($_GPC['dispatchprice']),
                    'freeprice' => trim($_GPC['freeprice']),
                    'begintime' => trim($_GPC['begintime']),
                    'endtime' => trim($_GPC['endtime']),
                    'updatetime' => TIMESTAMP,
                    'dateline' => TIMESTAMP,
                    'delivery_within_days' => intval($_GPC['delivery_within_days']),
                    'delivery_radius' => floatval($_GPC['delivery_radius']),
                    'not_in_delivery_radius' => intval($_GPC['not_in_delivery_radius'])
                );

                if (istrlen($data['title']) == 0) {
                    message('没有输入标题.', '', 'error');
                }
                if (istrlen($data['title']) > 30) {
                    message('标题不能多于30个字。', '', 'error');
                }
                if (istrlen($data['tel']) == 0) {
//                    message('没有输入联系电话.', '', 'error');
                }
                if (istrlen($data['address']) == 0) {
                    //message('请输入地址。', '', 'error');
                }

                if (is_array($_GPC['thumbs'])) {
//                    $data['thumb_url'] = serialize($_GPC['thumbs']);
                }

                if (!empty($id)) {
                    unset($data['dateline']);
                    pdo_update($this->table_stores, $data, array('id' => $id, 'weid' => $_W['uniacid']));
                } else {
                    $shoptotal = pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename($this->table_stores) . " WHERE weid=:weid", array(':weid' => $this->_weid));
                    if (!empty($config['storecount'])) {
                        if ($shoptotal >= $config['storecount']) {
                            message('您只能添加' . $config['storecount'] . '家门店');
                        }
                    }
                    $id = pdo_insert($this->table_stores, $data);
                }

                if (is_array($_GPC['begintimes'])) {
                    foreach ($_GPC['begintimes'] as $oid => $val) {
                        $begintime = $_GPC['begintimes'][$oid];
                        $endtime = $_GPC['endtimes'][$oid];
                        if (empty($begintime) || empty($endtime)) {
                            continue;
                        }

                        $data = array(
                            'weid' => $weid,
                            'storeid' => $id,
                            'begintime' => $begintime,
                            'endtime' => $endtime,
                        );
                        pdo_update('weisrc_dish_mealtime', $data, array('id' => $id));
                    }
                }

                //增加
                if (is_array($_GPC['newbegintime'])) {
                    foreach ($_GPC['newbegintime'] as $nid => $val) {
                        $begintime = $_GPC['newbegintime'][$nid];
                        $endtime = $_GPC['newendtime'][$nid];
                        if (empty($begintime) || empty($endtime)) {
                            continue;
                        }

                        $data = array(
                            'weid' => $weid,
                            'storeid' => $id,
                            'begintime' => $begintime,
                            'endtime' => $endtime,
                            'dateline' => TIMESTAMP
                        );
                        pdo_insert('weisrc_dish_mealtime', $data);
                    }
                }
                message('操作成功!', $url);
            }
        } elseif ($operation == 'delete') {
            $id = intval($_GPC['id']);
            $store = pdo_fetch("SELECT id FROM " . tablename($this->table_stores) . " WHERE id = '$id'");
            if (empty($store)) {
                message('抱歉，不存在或是已经被删除！', $this->createWebUrl('stores', array('op' => 'display')), 'error');
            }
            pdo_delete($this->table_stores, array('id' => $id, 'weid' => $_W['uniacid']));
            message('删除成功！', $this->createWebUrl('stores', array('op' => 'display')), 'success');
        }

        $echarts_path = $_W['siteroot'] . "/addons/weisrc_dish/template/js/dist";
        include $this->template('data');
    }

    public function updateFansFirstStore($from_user, $storeid)
    {
        global $_GPC, $_W;
        $weid = $this->_weid;
        $fans = pdo_fetch("SELECT * FROM " . tablename($this->table_fans) . " WHERE from_user = :from_user AND weid=:weid", array(':from_user' => $from_user, ':weid' => $this->_weid));
        if (!empty($fans) && $fans['storeid'] == 0) {
            pdo_update($this->table_fans, array('storeid' => $storeid), array('id' => $fans['id']));
        }
    }

    public function updateFansData($from_user)
    {
        global $_GPC, $_W;
        $weid = $this->_weid;
        $fans = pdo_fetch("SELECT * FROM " . tablename($this->table_fans) . " WHERE from_user = :from_user AND weid=:weid", array(':from_user' => $from_user, ':weid' => $this->_weid));
        if (!empty($fans)) {
            $count = pdo_fetchcolumn("SELECT COUNT(1) FROM " . tablename($this->table_order) . "  WHERE weid = :weid AND status=3 AND from_user = :from_user", array(':weid' => $weid, ':from_user' => $from_user));
            $totalprice = pdo_fetchcolumn("SELECT sum(totalprice) FROM " . tablename($this->table_order) . "  WHERE weid = :weid AND status=3 AND from_user = :from_user", array(':weid' => $weid, ':from_user' => $from_user));
            $avgprice = pdo_fetchcolumn("SELECT AVG(totalprice) FROM " . tablename($this->table_order) . "  WHERE weid = :weid AND status=3 AND from_user = :from_user", array(':weid' => $weid, ':from_user' => $from_user));

            pdo_update($this->table_fans, array('totalprice' => $totalprice, 'avgprice' => $avgprice, 'totalcount' => $count), array('id' => $fans['id']));
        }
    }

    public function set_commission($orderid)
    {
        global $_GPC, $_W;
        $weid = $this->_weid;

        $setting = $this->getSetting();
        if ($setting['is_commission'] == 1) {
            $order = pdo_fetch("SELECT * FROM " . tablename($this->table_order) . " WHERE id=:id AND weid=:weid LIMIT 1", array(':id' => $orderid, ':weid' => $this->_weid));
            if ($order) {
                $fans = pdo_fetch("SELECT * FROM " . tablename($this->table_fans) . " WHERE from_user=:from_user AND weid=:weid LIMIT 1", array(':from_user' => $order['from_user'], ':weid' => $this->_weid));
                if ($fans['agentid'] > 0) {
                    $agent = pdo_fetch("SELECT * FROM " . tablename($this->table_fans) . " WHERE id=:id AND weid=:weid LIMIT 1", array(':id' => $fans['agentid'], ':weid' => $this->_weid));

                    $totalprice = floatval($order['totalprice']);
                    if ($agent) {
                        $commission1_rate_max = floatval($setting['commission1_rate_max']);
                        $commission1_value_max = intval($setting['commission1_value_max']);
                        $commission1_price = $totalprice * $commission1_rate_max / 100;
                        if ($commission1_value_max > 0) {
                            if ($commission1_price > $commission1_value_max) {
                                $commission1_price = $commission1_value_max;
                            }
                        }

                        $data = array(
                            'weid' => $weid,
                            'storeid' => $order['storeid'],
                            'orderid' => $order['id'],
                            'agentid' => $fans['agentid'],
                            'ordersn' => $order['ordersn'],
                            'level' => 1,
                            'from_user' => $order['from_user'],
                            'price' => $commission1_price,
                            'status' => $setting['commission_settlement'] == 1 ? 1 : 0,
                            'dateline' => TIMESTAMP
                        );
                        pdo_insert($this->table_commission, $data);
                        if ($setting['commission_settlement'] == 1) {
                            $this->setFansCoin($agent['from_user'], $commission1_price, "单号{$order['ordersn']}一级佣金奖励");
                        }
                    }
                    //2级
                    if ($setting['commission_level'] > 1) {
                        if ($agent['agentid'] > 0) {
                            $agent2 = pdo_fetch("SELECT * FROM " . tablename($this->table_fans) . " WHERE id=:id AND weid=:weid LIMIT 1", array(':id' => $agent['agentid'], ':weid' => $this->_weid));
                            $commission2_rate_max = floatval($setting['commission2_rate_max']);
                            $commission2_value_max = intval($setting['commission2_value_max']);
                            $commission2_price = $totalprice * $commission2_rate_max / 100;
                            if ($commission2_value_max > 0) {
                                if ($commission2_price > $commission2_value_max) {
                                    $commission2_price = $commission2_value_max;
                                }
                            }

                            $data = array(
                                'weid' => $weid,
                                'storeid' => $order['storeid'],
                                'orderid' => $order['id'],
                                'agentid' => $agent['agentid'],
                                'ordersn' => $order['ordersn'],
                                'level' => 2,
                                'from_user' => $order['from_user'],
                                'price' => $commission2_price,
                                'status' => $setting['commission_settlement'] == 1 ? 1 : 0,
                                'dateline' => TIMESTAMP
                            );
                            pdo_insert($this->table_commission, $data);
                            if ($setting['commission_settlement'] == 1) {
                                $this->setFansCoin($agent2['from_user'], $commission1_price, "单号{$order['ordersn']}佣金奖励");
                            }
                        }
                    }
                }
            }
        }
    }

    //卡号码
    public function get_save_number($weid)
    {
        global $_W, $_GPC;
        $save_number = pdo_fetch("select savenumber from " . tablename($this->table_savewine_log) . " where weid =:weid order by id desc limit 1", array(':weid' => $weid));
        if (!empty($save_number)) {
            return intval($save_number['savenumber']) + 1;
        } else {
            return 1000001;
        }
    }

    public function doWebCheckOrder()
    {
        global $_W, $_GPC;
        $storeid = intval($_GPC['storeid']);
        if ($storeid == 0) {
            $order = pdo_fetch("SELECT 1 FROM " . tablename($this->table_order) . " WHERE weid=:weid AND status=0 LIMIT 1", array(':weid' => $this->_weid));
            $service = pdo_fetch("SELECT content FROM " . tablename($this->table_service_log) . " WHERE weid=:weid AND status=0 ORDER BY id DESC LIMIT 1", array(':weid' => $this->_weid));
        } else {
            $order = pdo_fetch("SELECT 1 FROM " . tablename($this->table_order) . " WHERE weid=:weid AND status=0 AND storeid=:storeid LIMIT 1", array(':weid' => $this->_weid, ':storeid' => $storeid));
            $service = pdo_fetch("SELECT content FROM " . tablename($this->table_service_log) . " WHERE weid=:weid AND status=0 AND storeid=:storeid ORDER BY id DESC LIMIT 1", array(':weid' => $this->_weid, ':storeid' => $storeid));
        }

        if ($service) {
            if (!empty($service['content'])) {
                exit($service['content']);
            }
        }
        if ($order) {
            exit('success');
        }
    }

    public function doMobileCheckOrder()
    {
        global $_W, $_GPC;
        $storeid = intval($_GPC['storeid']);
        if ($storeid == 0) {
            $order = pdo_fetch("SELECT 1 FROM " . tablename($this->table_order) . " WHERE weid=:weid AND status=0 LIMIT 1", array(':weid' => $this->_weid));
            $service = pdo_fetch("SELECT content FROM " . tablename($this->table_service_log) . " WHERE weid=:weid AND status=0 ORDER BY id DESC LIMIT 1", array(':weid' => $this->_weid));
        } else {
            $order = pdo_fetch("SELECT 1 FROM " . tablename($this->table_order) . " WHERE weid=:weid AND status=0 AND storeid=:storeid LIMIT 1", array(':weid' => $this->_weid, ':storeid' => $storeid));
            $service = pdo_fetch("SELECT content FROM " . tablename($this->table_service_log) . " WHERE weid=:weid AND status=0 AND storeid=:storeid ORDER BY id DESC LIMIT 1", array(':weid' => $this->_weid, ':storeid' => $storeid));
        }

//        if ($service) {
//            if (!empty($service['content'])) {
//                exit($service['content']);
//            }
//        }
        if ($order) {
            exit('success');
        }
    }

    public function doWebOperatorNotice()
    {
        global $_W, $_GPC;
        $storeid = intval($_GPC['storeid']);
        $returnid = $this->checkPermission($storeid);

        $operation = !empty($_GPC['op']) ? $_GPC['op'] : 'new';
        if ($storeid == 0) {
            $service = pdo_fetch("SELECT * FROM " . tablename($this->table_service_log) . " WHERE weid=:weid AND status=0 ORDER by id DESC LIMIT 1", array(':weid' => $this->_weid));
            if ($operation == 'new') {
                pdo_update($this->table_service_log, array('status' => 1), array('id' => $service['id']));
            }
            if ($operation == 'all') {
                pdo_update($this->table_service_log, array('status' => 1), array('weid' => $this->_weid));
            }
            message('操作成功！', $this->createWebUrl('allorder', array('op' => 'display', 'storeid' => $storeid)),
                'success');
        } else {
            $service = pdo_fetch("SELECT * FROM " . tablename($this->table_service_log) . " WHERE weid=:weid AND status=0 AND storeid=:storeid ORDER by id DESC LIMIT 1", array(':weid' => $this->_weid, ':storeid' => $storeid));
            if ($operation == 'new') {
                pdo_update($this->table_service_log, array('status' => 1), array('id' => $service['id']));
            }
            if ($operation == 'all') {
                pdo_update($this->table_service_log, array('status' => 1), array('weid' => $this->_weid, 'storeid' => $storeid));
            }
            message('操作成功！', $this->createWebUrl('order', array('op' => 'display', 'storeid' => $storeid)), 'success');
        }
    }

    public function doWebRetreat()
    {
        global $_W, $_GPC;
        $storeid = intval($_GPC['storeid']);
        $returnid = $this->checkPermission($storeid);

        $orderid = intval($_GPC['orderid']);
        $goodsid = intval($_GPC['goodsid']);

        $order = pdo_fetch("SELECT * FROM " . tablename($this->table_order) . " WHERE weid=:weid AND id=:orderid
        ORDER by id
DESC LIMIT 1", array(':weid' => $this->_weid, ':orderid' => $orderid));
        if (empty($order)) {
            message('订单不存在!');
        }


        $item = pdo_fetch("SELECT * FROM " . tablename($this->table_order_goods) . " WHERE weid=:weid AND goodsid=:goodsid AND orderid=:orderid ORDER by id
DESC LIMIT 1", array(':weid' => $this->_weid, ':goodsid' => $goodsid, ':orderid' => $orderid));

        if (empty($item)) {
            message('商品不存在!');
        }

        $total = intval($item['total']);
        if ($total == 1) {
            $goodsprice = $item['price'];
            pdo_delete($this->table_order_goods, array('id' => $item['id']));
        } else {
            $price = floatval($item['price']);
            $goodsprice = $total * $price;
            $total = $total - 1;
            pdo_update($this->table_order_goods, array('total' => $total), array('id' => $item['id']));
        }

        $totalprice = floatval($order['totalprice']) - $goodsprice;
        pdo_update($this->table_order, array('totalprice' => $totalprice), array('weid' => $this->_weid, 'id' => $orderid));

        $paylog = pdo_fetch("SELECT * FROM " . tablename('core_paylog') . " WHERE tid=:tid AND uniacid=:uniacid AND status=0 AND module='weisrc_dish'
ORDER BY plid
DESC LIMIT 1", array(':tid' => $orderid, ':uniacid' => $this->_weid));
        if (!empty($paylog)) {
            pdo_update('core_paylog', array('fee' => $_GPC['updateprice']), array('plid' => $paylog['plid']));
        }
        if ($storeid == 0) {
            message('操作成功！', $this->createWebUrl('allorder', array('op' => 'detail', 'storeid' => $storeid, 'id' => $orderid)), 'success');
        } else {
            message('操作成功！', $this->createWebUrl('order', array('op' => 'detail', 'id' => $orderid, 'storeid' => $storeid)), 'success');
        }
    }

    //设置会员金额
    public function setFansCoin($from_user, $credit2, $remark)
    {
        load()->model('mc');
        load()->func('compat.biz');
        $uid = mc_openid2uid($from_user);
        $fans = mc_fetch($uid, array("credit2"));
        if (!empty($fans)) {
            $uid = intval($fans['uid']);
            $log = array();
            $log[0] = $uid;
            $log[1] = $remark;
            mc_credit_update($uid, 'credit2', $credit2, $log);
        }
    }

    public function exportexcel($data = array(), $title = array(), $filename = 'report')
    {
        header("Content-type:application/octet-stream");
        header("Accept-Ranges:bytes");
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=" . $filename . ".xls");
        header("Pragma: no-cache");
        header("Expires: 0");
        //导出xls 开始
        if (!empty($title)) {
            foreach ($title as $k => $v) {
                $title[$k] = iconv("UTF-8", "GB2312", $v);
            }
            $title = implode("\t", $title);
            echo "$title\n";
        }
        if (!empty($data)) {
            foreach ($data as $key => $val) {
                foreach ($val as $ck => $cv) {
                    $data[$key][$ck] = iconv("UTF-8", "GB2312", $cv);
                }
                $data[$key] = implode("\t", $data[$key]);
            }
            echo implode("\n", $data);
        }
    }

    //设置订单积分
    public function setOrderCredit($orderid, $add = true)
    {
        $order = pdo_fetch("SELECT * FROM " . tablename($this->table_order) . " WHERE id=:id LIMIT 1", array(':id' => $orderid));
        if (empty($order)) {
            return false;
        }

        $ordergoods = pdo_fetchall("SELECT goodsid, total FROM " . tablename($this->table_order_goods) . " WHERE orderid = :orderid", array(':orderid' => $orderid));
        if (!empty($ordergoods)) {
            $credit = 0.00;
            $sql = 'SELECT `credit` FROM ' . tablename($this->table_goods) . ' WHERE `id` = :id';
            foreach ($ordergoods as $goods) {
                $goodsCredit = pdo_fetchcolumn($sql, array(':id' => $goods['goodsid']));
                $credit += $goodsCredit * floatval($goods['total']);
            }
        }

        //增加积分
        if (!empty($credit)) {
            load()->model('mc');
            load()->func('compat.biz');
            $uid = mc_openid2uid($order['from_user']);
            $fans = fans_search($uid, array("credit1"));
            if (!empty($fans)) {
                $uid = intval($fans['uid']);
                $remark = $add == true ? '微点餐积分奖励 订单ID:' . $orderid : '微点餐积分扣除 订单ID:' . $orderid;
                $log = array();
                $log[0] = $uid;
                $log[1] = $remark;
                mc_credit_update($uid, 'credit1', $credit, $log);
            }
        }
        pdo_update($this->table_order, array('credit' => $credit), array('id' => $orderid));
        return true;
    }

    //入口设置
    public function doWebSetRule()
    {
        global $_W;
        $rule = pdo_fetch("SELECT id FROM " . tablename('rule') . " WHERE module = 'weisrc_dish' AND weid = '{$_W['uniacid']}' order by id desc");
        if (empty($rule)) {
            header('Location: ' . $_W['siteroot'] . create_url('rule/post', array('module' => 'weisrc_dish', 'name' => '微点餐')));
            exit;
        } else {
            header('Location: ' . $_W['siteroot'] . create_url('rule/post', array('module' => 'weisrc_dish', 'id' => $rule['id'])));
            exit;
        }
    }

    public function doWebUploadExcel()
    {
        global $_GPC, $_W;

        if ($_GPC['leadExcel'] == "true") {
            $filename = $_FILES['inputExcel']['name'];
            $tmp_name = $_FILES['inputExcel']['tmp_name'];

            $flag = $this->checkUploadFileMIME($_FILES['inputExcel']);
            if ($flag == 0) {
                message('文件格式不对.');
            }

            if (empty($tmp_name)) {
                message('请选择要导入的Excel文件！');
            }

            $msg = $this->uploadFile($filename, $tmp_name, $_GPC);

            if ($msg == 1) {
                message('导入成功！', referer(), 'success');
            } else {
                message($msg, '', 'error');
            }
        }
    }

    function uploadFile($file, $filetempname, $array)
    {
        //自己设置的上传文件存放路径
        $filePath = '../addons/weisrc_dish/upload/';
        include 'plugin/phpexcelreader/reader.php';

        $data = new Spreadsheet_Excel_Reader();
        $data->setOutputEncoding('utf-8');

        //注意设置时区
        $time = date("y-m-d-H-i-s"); //去当前上传的时间
        $extend = strrchr($file, '.');
        //上传后的文件名
        $name = $time . $extend;
        $uploadfile = $filePath . $name; //上传后的文件名地址

        if (copy($filetempname, $uploadfile)) {
            if (!file_exists($filePath)) {
                echo '文件路径不存在.';
                return;
            }
            if (!is_readable($uploadfile)) {
                echo("文件为只读,请修改文件相关权限.");
                return;
            }
            $data->read($uploadfile);
            error_reporting(E_ALL ^ E_NOTICE);
            $count = 0;
            for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) { //$=2 第二行开始
                //以下注释的for循环打印excel表数据
                for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
                    //echo "\"".$data->sheets[0]['cells'][$i][$j]."\",";
                }

                $row = $data->sheets[0]['cells'][$i];
                //message($data->sheets[0]['cells'][$i][1]);

                if ($array['ac'] == "category") {
                    $count = $count + $this->upload_category($row, TIMESTAMP, $array);
                } else if ($array['ac'] == "goods") {
                    $count = $count + $this->upload_goods($row, TIMESTAMP, $array);
                } else if ($array['ac'] == "store") {
                    $count = $count + $this->upload_store($row, TIMESTAMP, $array);
                }
            }
        }
        if ($count == 0) {
            $msg = "导入失败,数据已经存在！";
        } else {
            $msg = 1;
        }
        return $msg;
    }

    private function checkUploadFileMIME($file)
    {
        // 1.through the file extension judgement 03 or 07
        $flag = 0;
        $file_array = explode(".", $file ["name"]);
        $file_extension = strtolower(array_pop($file_array));

        // 2.through the binary content to detect the file
        switch ($file_extension) {
            case "xls" :
                // 2003 excel
                $fh = fopen($file ["tmp_name"], "rb");
                $bin = fread($fh, 8);
                fclose($fh);
                $strinfo = @unpack("C8chars", $bin);
                $typecode = "";
                foreach ($strinfo as $num) {
                    $typecode .= dechex($num);
                }
                if ($typecode == "d0cf11e0a1b11ae1") {
                    $flag = 1;
                }
                break;
            case "xlsx" :
                // 2007 excel
                $fh = fopen($file ["tmp_name"], "rb");
                $bin = fread($fh, 4);
                fclose($fh);
                $strinfo = @unpack("C4chars", $bin);
                $typecode = "";
                foreach ($strinfo as $num) {
                    $typecode .= dechex($num);
                }
                echo $typecode . 'test';
                if ($typecode == "504b34") {
                    $flag = 1;
                }
                break;
        }
        return $flag;
    }

    function upload_goods($strs, $time, $array)
    {
        global $_W;
        $insert = array();

        if (empty($strs[1])) {
            return 0;
        }

        //类别处理
        $category = pdo_fetch("SELECT id FROM " . tablename('weisrc_dish_category') . " WHERE name=:name AND weid=:weid AND storeid=:storeid", array(':name' => trim($strs[2]), ':weid' => $_W['uniacid'], ':storeid' => $array['storeid']));
        $insert['pcate'] = empty($category) ? 0 : intval($category['id']);
        $insert['title'] = $strs[1];
        $insert['thumb'] = $strs[3];
        $insert['unitname'] = $strs[4];
        $insert['description'] = $strs[5];
        $insert['taste'] = $strs[6];
        $insert['marketprice'] = $strs[7];
        $insert['productprice'] = $strs[8];
        $insert['subcount'] = $strs[9];
        $insert['credit'] = $strs[10];
        $insert['displayorder'] = $strs[11];
        $insert['dateline'] = TIMESTAMP;
        $insert['status'] = 1;
        $insert['recommend'] = 0;
        $insert['ccate'] = 0;
        $insert['storeid'] = $array['storeid'];
        $insert['weid'] = $_W['uniacid'];

        $goods = pdo_fetch("SELECT * FROM " . tablename('weisrc_dish_goods') . " WHERE title=:title AND weid=:weid AND storeid=:storeid", array(':title' => $strs[1], ':weid' => $_W['uniacid'], ':storeid' => $array['storeid']));

        if (empty($goods)) {
            return pdo_insert('weisrc_dish_goods', $insert);
        } else {
            return 0;
        }
    }

    function upload_category($strs, $time, $array)
    {
        global $_W;

        if (empty($strs[1])) {
            return 0;
        }

        $insert = array();
        $insert['name'] = $strs[1];
        $insert['parentid'] = 0;
        $insert['displayorder'] = 0;
        $insert['enabled'] = 1;
        $insert['storeid'] = $array['storeid'];
        $insert['weid'] = $_W['uniacid'];

        $category = pdo_fetch("SELECT * FROM " . tablename('weisrc_dish_category') . " WHERE name=:name AND weid=:weid AND storeid=:storeid", array(':name' => $strs[1], ':weid' => $_W['uniacid'], ':storeid' => $array['storeid']));

        if (empty($category)) {
            return pdo_insert('weisrc_dish_category', $insert);
        } else {
            return 0;
        }
    }

    function upload_store($strs, $time, $array)
    {
        global $_W;

        if (empty($strs[1])) {
            return 0;
        }

        $insert = array();
        $insert['weid'] = $_W['uniacid'];
        $insert['title'] = $strs[1];
        $insert['info'] = $strs[2];
        $insert['logo'] = $strs[3];
        $insert['content'] = $strs[4];
        $insert['tel'] = $strs[5];
        $insert['address'] = $strs[6];
        $insert['place'] = $strs[6];
        $insert['hours'] = $strs[7];
//        $insert['location_p'] = $strs[8];
//        $insert['location_c'] = $strs[9];
//        $insert['location_a'] = $strs[10];
        $insert['password'] = '';
        $insert['recharging_password'] = '';
        $insert['is_show'] = 1;
        $insert['areaid'] = 0;
        $insert['lng'] = '0.000000000';
        $insert['lat'] = '0.000000000';
        $insert['enable_wifi'] = 1;
        $insert['enable_card'] = 1;
        $insert['enable_room'] = 1;
        $insert['enable_park'] = 1;
        $insert['updatetime'] = TIMESTAMP;
        $insert['dateline'] = TIMESTAMP;

        $store = pdo_fetch("SELECT * FROM " . tablename('weisrc_dish_stores') . " WHERE title=:title AND weid=:weid LIMIT 1", array(':title' => $strs[1], ':weid' => $_W['uniacid']));

        if (empty($store)) {
            return pdo_insert('weisrc_dish_stores', $insert);
        } else {
            return 0;
        }
    }

    public function message($error, $url = '', $errno = -1)
    {
        $data = array();
        $data['errno'] = $errno;
        if (!empty($url)) {
            $data['url'] = $url;
        }
        $data['error'] = $error;
        echo json_encode($data);
        exit;
    }

    //----------------------以下是接口定义实现，第三方应用可根据具体情况直接修改----------------------------
    function sendFreeMessage($msg)
    {
        $msg['reqTime'] = number_format(1000 * time(), 0, '', '');
        $content = $msg['memberCode'] . $msg['msgDetail'] . $msg['deviceNo'] . $msg['msgNo'] . $msg['reqTime'] . $this->feyin_key;
        $msg['securityCode'] = md5($content);
        $msg['mode'] = 2;

        return $this->sendMessage($msg);
    }

    function sendFormatedMessage($msgInfo)
    {
        $msgInfo['reqTime'] = number_format(1000 * time(), 0, '', '');
        $content = $msgInfo['memberCode'] . $msgInfo['customerName'] . $msgInfo['customerPhone'] . $msgInfo['customerAddress'] . $msgInfo['customerMemo'] . $msgInfo['msgDetail'] . $msgInfo['deviceNo'] . $msgInfo['msgNo'] . $msgInfo['reqTime'] . $this->feyin_key;

        $msgInfo['securityCode'] = md5($content);
        $msgInfo['mode'] = 1;

        return $this->sendMessage($msgInfo);
    }

    function sendMessage($msgInfo)
    {
        $client = new HttpClient(FEYIN_HOST, FEYIN_PORT);
        if (!$client->post('/api/sendMsg', $msgInfo)) { //提交失败
            return 'faild';
        } else {
            return $client->getContent();
        }
    }

    function queryState($msgNo)
    {
        $now = number_format(1000 * time(), 0, '', '');
        $client = new HttpClient(FEYIN_HOST, FEYIN_PORT);
        if (!$client->get('/api/queryState?memberCode=' . $this->member_code . '&reqTime=' . $now . '&securityCode=' . md5($this->member_code . $now . $this->feyin_key . $msgNo) . '&msgNo=' . $msgNo)) { //请求失败
            return 'faild';
        } else {
            return $client->getContent();
        }
    }

    function listDevice()
    {
        $now = number_format(1000 * time(), 0, '', '');
        $client = new HttpClient(FEYIN_HOST, FEYIN_PORT);
        if (!$client->get('/api/listDevice?memberCode=' . $this->member_code . '&reqTime=' . $now . '&securityCode=' . md5($this->member_code . $now . $this->feyin_key))) { //请求失败
            return 'faild';
        } else {
            /***************************************************
             * 解释返回的设备状态
             * 格式：
             * <device id="4600006007272080">
             * <address>广东**</address>
             * <since>2010-09-29</since>
             * <simCode>135600*****</simCode>
             * <lastConnected>2011-03-09  19:39:03</lastConnected>
             * <deviceStatus>离线 </deviceStatus>
             * <paperStatus></paperStatus>
             * </device>
             **************************************************/

            $xml = $client->getContent();
            $sxe = new SimpleXMLElement($xml);
            foreach ($sxe->device as $device) {
                $id = $device['id'];
                echo "设备编码：$id    ";

                $deviceStatus = $device->deviceStatus;
                echo "状态：$deviceStatus";
                echo '<br>';
            }
        }
    }

    function listException()
    {
        $now = number_format(1000 * time(), 0, '', '');
        $client = new HttpClient(FEYIN_HOST, FEYIN_PORT);
        if (!$client->get('/api/listException?memberCode=' . MEMBER_CODE . '&reqTime=' . $now . '&securityCode=' . md5(MEMBER_CODE . $now . $this->feyin_key))) { //请求失败
            return 'faild';
        } else {
            return $client->getContent();
        }
    }

    function feiyinstatus($code)
    {
        switch ($code) {
            case 0:
                $text = "正常";
                break;
            case -1:
                $text = "IP地址不允许";
                break;
            case -2:
                $text = "关键参数为空或请求方式不对";
                break;
            case -3:
                $text = "客户编码不对";
                break;
            case -4:
                $text = "安全校验码不正确";
                break;
            case -5:
                $text = "请求时间失效";
                break;
            case -6:
                $text = "订单内容格式不对";
                break;
            case -7:
                $text = "重复的消息";
                break;
            case -8:
                $text = "消息模式不对";
                break;
            case -9:
                $text = "服务器错误";
                break;
            case -10:
                $text = "服务器内部错误";
                break;
            case -111:
                $text = "打印终端不属于该账户";
                break;
            default:
                $text = "未知";
                break;
        }
        return $text;
    }
}